2

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 Answer 1

6

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';

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.