Javascript strings are immutable but reassigning by index does not throw error

Viewed 102

This is the code

let name = 'John';
name[1] = 'a';
name[2] = 'n';
name[3] = 'e';

I know Javascript strings are immutable. The lines 2, 3 and 4 are not gonna work and if I console.log(name), the output will be 'John'. But why is Js not throwing an error for line 2, 3, 4 ?

1 Answers

In sloppy mode, certain types of failures are frequently silent. In this case, the index properties of the string are non-writable:

console.log(
  Object.getOwnPropertyDescriptor('foo', 1)
);

And assigning to a non-writable property will:

  • In sloppy mode, fail silently
  • In strict mode, throw an error

Specifically, this logic is implemented in PutValue.

If succeeded is false and V.[[Strict]] is true, throw a TypeError exception.

If you want to make these sorts of silent bugs into explicit errors, use strict mode:

'use strict';
let name = 'John';
name[1] = 'a';

Related