0

I'm going crazy with the concept of immutability in Javascript. The concept is explained like "after it has been created, it can never change." But what does it exactly mean? I understood the example of the content of a string

 var statement = "I am an immutable value";
 var otherStr = statement.slice(8, 17);

The second line in no way changes the string in statement. But what about the methods? Can you give an example of immutability in methods? I hope you can help me, thank you.

GniruT
  • 731
  • 1
  • 6
  • 14
  • This is not in javascript but the same concept applies. http://stackoverflow.com/questions/279507/what-is-meant-by-immutable – toskv Oct 04 '15 at 18:11
  • [Related: _Why can't I add properties to a string object in javascript?_](http://stackoverflow.com/questions/5201138/why-cant-i-add-properties-to-a-string-object-in-javascript) – James Thorpe Oct 04 '15 at 18:16

1 Answers1

1

An example of where immutability in a string helps would be when you pass a string to a function so it can be used later (eg. in a setTimeout).

var s = "I am immutable";

function capture(a) {
  setTimeout(function() { // set a timeout so this happens after the s is changed
    console.log("old value: " + a); // should have the old value: 'I am immutable'
  }, 2000);
}

capture(s); // send s to a function that sets a timeout.
s += "Am I really?"; // change it's value
console.log("new value: " + s); // s has the new value here

This way you can be certain that no matter what changes you make to s in the global scope will not affect the value of a (old s) in the scope of the capture function.

You can check this working in this plunker

toskv
  • 30,680
  • 7
  • 72
  • 74