0

The following code doesn't affect string str but won't generate any error or exception either, why?

start();

function start(){
  var str = 'abcdef';
  for(var i=0;i<5;i++){
    str[i] = str[i+1];
    console.log(str[i]);
  }
  console.log(str);
}

The output looks like following:

a
b
c
d
e
abcdef
0

1 Answer 1

2

Yes, they are immutable.

If you enable strict mode, the silent failures will turn into explicit errors:

'use strict';

start();

function start(){
  var str = 'abcdef';
  for(var i=0;i<5;i++){
    str[i] = str[i+1];
    console.log(str[i]);
  }
  console.log(str);
}

(Enabling strict mode is generally a good idea, it can make debugging easier)

This isn't a string-specific issue - trying to assign to any read-only property will throw in strict mode, and will fail silently in sloppy mode:

'use strict';
var str = 'a';
console.log(Object.getOwnPropertyDescriptor(str, '0'));

const obj = {};
Object.defineProperty(obj, 'prop', { value: 'value' });
console.log(Object.getOwnPropertyDescriptor(obj, 'prop'));
obj.prop = 5;

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.