Common Bugs with Strings
Five string traps that trip beginners and intermediates alike.
From Bee: "I see this exact bug in beginners every week. Read it once, and you'll spot it on yourself before it bites."
Treating string as mutable
js
let s = "hello";
s[0] = "H"; // silently fails
console.log(s); // "hello"⚠️
Why this happens
Strings are immutable in JS, Python, and Java. Index assignment does nothing or errors.✅
The fix
Build a new string: "H" + s.slice(1).Forgetting to escape quotes
js
const greeting = "He said "hi""; // syntax error⚠️
Why this happens
The middle quote ends the string early.✅
The fix
Escape: "He said \"hi\"" or use template literals: `He said "hi"`.Using == on strings in Java
java
String a = new String("hi");
String b = new String("hi");
a == b; // false
a.equals(b); // true⚠️
Why this happens
== compares references for objects in Java.✅
The fix
Always use .equals() for string content comparison.Slow string concatenation in a loop
java
String result = "";
for (int i = 0; i < 10000; i++) {
result += i; // creates a new String each time
}⚠️
Why this happens
Strings are immutable, so += creates a new string per iteration. O(n²).✅
The fix
Use StringBuilder in Java, "".join(parts) in Python, or array+join in JS.Locale-sensitive sort surprises
js
console.log(["b", "A", "c"].sort());
// ["A", "b", "c"] — uppercase sorts first⚠️
Why this happens
Default sort uses Unicode code points; uppercase letters come before lowercase.✅
The fix
arr.sort((a,b) => a.localeCompare(b)) for human-friendly sort.💡
Want the full lesson?
Read Strings — the complete lesson, or test yourself with the quiz.