0

Eloquent JavaScript says string values are immutable, as the first Stackoverflow question's answer : Understanding Javascript immutable variable

But if we write the following : var string = "hello world"; string = "permitted";, the string is really modified.

The answer I mentionned above just explain that objects are mutable, not the other values.

Since the string can be modified as I told you just above, does it mean that the string primitive value is automatically converted into an object when it succeeds a '=' ?

So the previous code would be strictly equivalent to : var string = new String("hello world"); string = new String("permitted"). That would explain why the string's value is modified.

Community
  • 1
  • 1
JarsOfJam-Scheduler
  • 2,809
  • 3
  • 31
  • 70

2 Answers2

2

You need to distinguish between reassignment and mutation:

let x = "abc";

x = "123"; // reassignment
console.log(x);

x[0] = "9"; // mutation
console.log(x);

After the mutation x still contains "123", because Strings are immutable. If Strings were mutable it would contain "912" of course.

You must also distinguish between the following terms:

  • Variable

With this declaration let x = "abc" you declare a variable x and initialize it with the value "abc".

  • Identifier

Whenever x is used in your code (except when declaring) it is just an identifier and have to be bound to the corresponding variable declaration by Javascript. Please note that you can have several declarations like let x = "abc" in different scopes and hence name binding is necessary:

let x = "abc";

{ // another scope
  let x = "123";

  { // and yet another scope
    console.log(x); // which is the corresponding variable of this identifier?
  }
}

If you want to prevent that a variable can be reassigned, you can actually do this in ES2015:

const x = "abc";
x = "123"; // throws an Error

Notice that you modified the variable declaration to achieve this behavior.

  • When you say "`String`"s are immutable, you're speaking about the primitive value or about the object ? (because in JS, these both values exist) – JarsOfJam-Scheduler Sep 17 '16 at 22:11
  • @Lern-X A string `Object` is merely a `String` primitive wrapped in an `Object`: `let x = new String("abc")`. The `String` primitive is still immutable `x[0] = "x"` yields `"abc"`, but the wrapper isn't: `x.prop = true; x.prop` yields `true`. –  Sep 18 '16 at 05:18
1

Maybe a demonstration will show you what it means for a string to be immutable.

var stringobject = new String("test"); // or "test"; both yield same result
console.assert(stringobject.valueOf() === "test", "before");

stringobject[0] = "T"; // replace first char
console.assert(stringobject.valueOf() === "Test", "after");

console.log("Success?"); // or is it?
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592