- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- Strings in JavaScript for DSA
Strings
Strings in JavaScript for DSA
JavaScript strings cannot be changed. Every operation that looks like editing one is really building a new one, and that single fact explains most string performance problems.
Immutable means copied
You cannot assign to a character - s[0] = "x" silently does nothing. Any change produces a whole new string.
Building a string, the slow way
javascript
// A new string on every iteration.
function repeatSlow(char, times) {
let out = ""
for (let i = 0; i < times; i++) out += char
return out
}
// Collect the pieces, join once at the end.
function repeatFast(char, times) {
const parts = []
for (let i = 0; i < times; i++) parts.push(char)
return parts.join("")
}