This story is unavailable.

Mutable & Immutable in JavaScript

In simple terms mutable means “ subject to change or alteration” and immutable means “unalterable”. Now, what that means in JavaScript Programming context is:

Immutable

var name = ‘Bill’;
var full_name = name.concat(‘ Gates’);

In the above case, full_name equals to Bill Gates and name equals Bill, stating that once string value is created, it can never change. In fact, no string methods change the string they operate on, they all return new strings. The reason being that strings in javascript are immutable.

var sum = 2 + 3;

Here, sum equals 5. But that does not change the initial values 2 and 3. In fact, numbers, strings and booleans are all immutable.

Mutable

var arr = [1];
var new_arr = arr.push(2);

Here, the original array arr gets altered and it equals to [1,2]. And new_arr equals to 2. As, you can see that in case of array or objects one can alter the original value, leading to the result that they are mutable.

Note: there are no such list type in JavsScript that is immutable. But can use custom built libraries for such lists, e.g. ImmutableJs by facebook.

Did you know?

As per the javascript best practices guide. The best way to always create a new object is with following notation:

const obj = {}

Reason being that as the objects are mutable, one can easily alter it and add properties to it later on. While const ensures that the variable obj does not get re-declared to some other object accidentally later on in the code.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.