Berat Bozkurt

Berat Bozkurt




Related Posts

How to Fix Errors in Frontend 101
21 Ekim 2024

How to Fix Errors in Frontend 101

How to Use Multiple Github Accounts on macOS?
07 Ekim 2022

How to Use Multiple Github Accounts on macOS?

06 Eylül 2022

Javascript Tips #1

Immutable and Mutable in Javascript

23 Ekim 2024 • 1 view•
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.
We encounter this situation a lot in real life. From time to time, we keep searching for a solution to this problem. We solve it, but when it comes up again, we need to search again. Now I will talk about how to solve this more deeply and a few methods. But first, let's see which array functions create mutable.
  • .pop()
  • .push()
  • .shift()
  • .unshift()
  • .reverse()
  • .sort()
  • .splice()
Functions that do not create mutation, that is, are immutable;
  • .slice()
  • .concat()
  • .map()
  • .filter()
  • .redue()
  • .find()
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
Push
Shift
Unshift
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…
  • Resources — https://www.sitepoint.com/immutable-array-methods-javascript/
•
Share on X (Twitter)