create immutable object in javascript 1

create immutable object in javascript

let x = {name: "blood", color: "red"}
let {...y} = x

// let's update the value of "x"
x.name = "strawberry"

console.log(x) // will return {name: "strawberry", color: "red"}
console.log(y) // will return {name: "blood", color: "red"}
/* "y" haven't changed because it copied the value of "x" and made himself
a whole separated ohject, instead of just coping the reference of "x"
(reference copy case:- let y = x) */
/* NOTE: get some youtube classes about javascript reference type and primitive
data types, if you're not clear enough about what i mean by "reference" */

Here is what the above code is Doing:
1. We created an object “x” with two properties “name” and “color”.
2. We created another object “y” and used the spread operator to copy the
properties of “x” into “y”.
3. We changed the value of “name” property of “x” to “strawberry”.
4. We logged the value of “x” and “y” to the console.

As you can see, the value of “y” didn’t change. This is because the spread
operator creates a new object and copies the properties of the old object
into the new object.

The spread operator is a great way to create a copy of an object.

Similar Posts