loading likes...23 October, 2024 126 total views

Immutable and Mutable in Javascript

Immutable and Mutable in Javascript

If there is a subject I want to learn, I want it to be practical rather than memorized. Therefore, I have a lot of lack of knowledge in some technical and terminological subjects. I am trying to improve myself by working on these in these times. I am keeping notes of what I have learned in this new process, but I asked why I am not writing it on my blog, and here I am.


Let's understand better with examples.

const arr = [1,2,3,4];
const newArr = arr;

newArr.push(5);

console.log(arr) // [1,2,3,4,5]
console.log(newArr) // [1,2,3,4,5]

Here, when we transfer the arr variable to the newArr variable, we are also transferring its reference as well as the values. In other words, let me explain it like this. The array variable is actually stored in an area in RAM. When I transfer it to the newArr, I also transfer the area in RAM. Therefore, when I add a new value to the newArr, I also add it to the arr. This is actually an example of mutable.

Functions that do not create mutation, that is, are immutable;

In cases where mutation occurs with some methods, we can use some techniques to prevent this. I will not explain them one by one because you can easily understand when you look at them.

Pop

const pop = arr => arr.slice(0,-1);

Push

const push = (arr, value) => [...arr,value];

Shift

const shift = arr => arr.slice(1);

Unshift

const unshift = (arr,value) => [value,...arr];

Reverse

const reverse = arr => [...arr].reverse();

Definitive solution (to prevent mutation)

const arr = [1,2,3,4,5,6]
const copy = [...arr] // You can do whatever you want with the copy variable.

No matter how much you read or listen to some topics, we can miss some points. At this point, by writing or telling, we can think more deeply about the places we are not sure about. This is what I am experiencing right now.

Hope to see you in the next articles…

Read Next
Open to new job opportunities
Immutable and Mutable in Javascript