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.

2

1 Answer 1

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

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

2 Comments

Hi, can we say the same if <s> is declared as <s = new String("I am immutable")>? Thanks
@GniruT yes, check this plnkr. plnkr.co/edit/UbObCDrYeFeixHAOWUqC?p=preview

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.