Common Bugs with Strings

📌 Common bugs · strings✍️ Written by Mark Sullivan📅 Reviewed 2026-04-12⏱ ~7 min read

Five string traps that trip beginners and intermediates alike.

Bee mascot
From Bee: "I see this exact bug in beginners every week. Read it once, and you'll spot it on yourself before it bites."
#1

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).
#2

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"`.
#3

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.
#4

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.
#5

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.

M
Mark Sullivan
Lead writer · 8 yrs full-stack

Mark started coding in 2017 after switching from financial analysis. She's built production systems in Python (Django) and JavaScript (Node + React) at two startups, and has taught intro programming at his local community college since 2022. He owns the curriculum for variables, functions, conditionals, and loops on this site. More about Mark →