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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.