Mutability And Immutability In JavaScript Explained In Detail
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
@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.
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:
- 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:
- 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.
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:
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.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.
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.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.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.
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.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.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.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.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.
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.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 āŗļø
Previously published at https://cloudaffle.com/post/mutability-vs-immutability-javascript
Create your free account to unlock your custom reading experience.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK