Why is there no replacement?

I wrote the following code why is the “a” character not replaced with 4?

var input = 'javascript is awesome'
var output = ''
for (var i = 0; i < input.length; i++) {
  if (input[i] === 'a') {
    output[i] = '4'
  } else {
    output[i] = input[i]
  }
  output += output[i]
}
console.log(output)

we can read string characters using index, but we can not modify characters of string since it’s immutable
and if you are trying to replace ‘a’ with ‘4’ use input.replace(‘a’, ‘4’) instead.

As @saurabhv749 said, strings cannot be editing via their index positions the way that arrays can.

Just to note, in some languages you can manipulate strings like that, but not in JS. In JS, strings are immutable.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.