8

Mutability And Immutability In JavaScript Explained In Detail

 3 years ago
source link: https://hackernoon.com/mutability-and-immutability-in-javascript-explained-in-detail-x7q33ag
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Mutability And Immutability In JavaScript Explained In Detail

5
heart.pngheart.pngheart.pngheart.png
light.pnglight.pnglight.pnglight.png
boat.pngboat.pngboat.pngboat.png
money.pngmoney.pngmoney.pngmoney.png

@manikManik

Out Of The Box Thinker, Love To Write Javascript And Python. "šŸŗ šŸ» gulp watch"

You would often hear the most seasoned react developers suggest using the spread operator to copy an array instead of simply assigning it to a new variable. This has to do with specific data types being a reference type in JavaScript, hence being mutable. The concept of mutability and immutability in JavaScript is essential to understand to avoid errors. Letā€™s dive deeper into the idea of mutability vs. immutability in JavaScript.

Primitive Types vs. Reference Types in JavaScript

The data assigned to a JavaScript variable can be of two types, the primitive type and the reference type. There is a difference in how JavaScript treats these two data types. To know how they are treated differently, letā€™s first understand the difference between primitive and reference types.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

Primitive Types

Primitive types are simple atomic pieces of data in JavaScript. Primitive types are always saved and accessed by the variable's value and not as a reference to another object. There are six primitive types in JavaScript:

0 reactions
heart.png
light.png
money.png
thumbs-down.png
  • undefined
  • boolean
  • number
  • strings
  • symbol

Reference types

Reference types are not simple atomic values but are objects that are made up of multiple properties assigned to them. They are stored as a reference in memory and not as independent values assigned to variables. There are three reference types in JavaScript:

0 reactions
heart.png
light.png
money.png
thumbs-down.png
  • objects
  • arrays
  • functions

How Primitive Types and Reference Types are Stored in Memory

How primitive types and reference types are stored in the memory is the basis of how they are different from each other. Letā€™s look at a few examples and try to understand how they utilize memory differently.

0 reactions
heart.png
light.png
money.png
thumbs-down.png

Memory Utilization by Primitive Types

As highlighted earlier, primitive types are stored as a single atomic value assigned to a variable in the memory. Letā€™s see this example:

0 reactions
heart.png
light.png
money.png
thumbs-down.png
let name = 'john';
let name2 = name;

Looking at the above example, I created a variableĀ nameĀ and assigned it a valueĀ 

john
. Now JavaScript will save this as a single atomic value in the memory. Now, if i create a new variableĀ 
name2
Ā and assign it a value of the variableĀ nameĀ JavaScript will go ahead and create a new space in the memory and allocate the same value of the variableĀ nameĀ and assign it to the variableĀ 
name2
. The new value assigned to the variableĀ 
name2
, is entirely separate from the variableĀ 
name
Ā and does not have any reference to it whatsoever.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Memory Utilization by Reference Types

Reference values are objects stored in memory and references to objects instead of dedicated places in memory, unlike primitive types. Letā€™s look at the following example to understand better how the reference types are saved in memory by JavaScript.

0 reactions
heart.png
light.png
money.png
thumbs-down.png
let person = {
    name: 'john',
    age: 22,
};

let person2 = person; 

Letā€™s just declared a variable calledĀ 

person
Ā which will contain an object containing theĀ nameĀ and theĀ ageĀ of the
person
object. Now I will go ahead and create another variable namedĀ 
person2
Ā and assign it the same
person
Ā object. This is where things start getting different as compared to the primitive types. In this case, JavaScript will save the
person2
object simply as a reference to theĀ 
person
Ā object.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

If you look at this image, you will realize that JavaScript here is actually pointing to the same object in the memory. Though it has created a new variable, as a value, that variable just is referring to the sameĀ 

person
object that we created previously.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Understanding Immutability and Mutability of Primitive and Reference Types in JavaScript

Since we are now clear with the primitive and reference types in JavaScript, we can easily understand the concept of mutability and immutability in JavaScript. Mutable can be changed or added to where immutable means something that cannot be changed or added. Primitive values in JavaScript cannot have anything added upon to them, they can only be re-assigned, and hence all primitive values in JavaScript are immutable. Let see this with an example.

0 reactions
heart.png
light.png
money.png
thumbs-down.png
let name = 'john';
let name2 = name;

console.log(name);
console.log(name2);

/*
 * john
 * john 
 */

let name2 = 'doe';

console.log(name);
console.log(name2);

/*
 * john
 * doe 
 */

Extending our previous example of primitive types, letā€™s print the values of both our variables, i.e.Ā 

name
Ā andĀ 
name2
Ā to the console and see what we get. As expected, both the variables return the valueĀ john. Now letā€™s reassign
name2
Ā toĀ 
doe
Ā and then again print the values of both the variables to the console. Now you see that the value of onlyĀ 
name2
Ā was re-assigned by JavaScript toĀ 
doe
, but the variableĀ 
name
Ā did not change. This showā€™s that JavaScript treats these 2 variables separately, althoughĀ 
name2
was originally copied from the variableĀ 
name
. This proves that the primitive values in JavaScript, in this case, strings, are immutable.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

Letā€™s try to replicate the same example for reference types as well. Picking up from our previous example, letā€™s print the values of bothĀ 

person
Ā and
person2
Ā objects to the console and see what we get.
0 reactions
heart.png
light.png
money.png
thumbs-down.png
let person = {
    name: 'john',
    age: 22,
};

let person2 = person; 

console.log(person);
console.log(person2);

/*
* {
* name: 'john',
* age: 22,
* }
*
* {
* name: 'john',
* age: 22,
* }
*/

We see two objects printed on the console with the same properties. Now I will change one of the properties of theĀ 

person2
Ā object and print them to the console again.
0 reactions
heart.png
light.png
money.png
thumbs-down.png
let person2.name = 'doe'; 

console.log(person);
console.log(person2);

/*
* {
* name: 'doe',
* age: 22,
* }
*
* {
* name: 'doe',
* age: 22,
* }
*/

You see that JavaScript has changedĀ 

person
Ā as well asĀ 
person2
. This is because theĀ 
person2
Ā object was created by referencing theĀ 
person
object. With reference types, JavaScript creates a reference to the same object, and the object remains mutable. Since the object is mutable, it can be changed, or a new property can be added.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

The Spread Operator

The spread operator was introduced in ES6 (more information on ES6) and lets you copy your objects safely and create a new instance of the object instead of merely referencing the previous object. Letā€™s look at the same example and see how we can copy an object and save a new instance of the variable's object.

0 reactions
heart.png
light.png
money.png
thumbs-down.png
let person = {
    name: 'john',
    age: 22,
};

let person2 = {...person};
let person2.name = 'doe';

console.log(person);
console.log(person2);

/*
* {
* name: 'john',
* age: 22,
* }
*
* {
* name: 'doe',
* age: 22,
* }
*/

Letā€™s take the same person object, and instead of assigning it directly to a variable this time, letā€™s use the spread operator to copy it. The spread operator can be used by prefixing three dotsĀ ā€¦Ā in front of the object that you want to copy and encapsulate it using the literal object syntax. This way, JavaScript creates a new object and stores it in the variableĀ 

person2
. Letā€™s try to change one of the properties ofĀ 
person2
. I will change the name toĀ 
doe
. Now letā€™s print both the object to the console and see what we get. You see, this time, we only changed the name property of the
person2
Ā object and not theĀ 
person
Ā object. This is because theĀ 
person2
was created and saved as a new object using the spread operator and not as a reference to theĀ 
person
Ā object.
0 reactions
heart.png
light.png
money.png
thumbs-down.png

PS: I have created an extensiveĀ JavaScript cheatsheet. It has been in a manner where it becomes easy for you to refer to each property and method for various JavaScript objects. It's absolutely free to download from the above link ā˜ŗļø

0 reactions
heart.png
light.png
money.png
thumbs-down.png

Previously published at https://cloudaffle.com/post/mutability-vs-immutability-javascript

0 reactions
heart.png
light.png
money.png
thumbs-down.png
5
heart.pngheart.pngheart.pngheart.png
light.pnglight.pnglight.pnglight.png
boat.pngboat.pngboat.pngboat.png
money.pngmoney.pngmoney.pngmoney.png
Share this story
Join Hacker Noon

Create your free account to unlock your custom reading experience.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK