Mutation vs Reassignment in JavaScript

Posted by

Reassignment vs Mutation in Javascript

Reassignment vs Mutation in Javascript

When working with arrays or objects in Javascript, it’s important to understand the difference between reassignment and mutation.

Reassignment

Reassignment is when you assign a new value to a variable. When you reassign a new value to a variable that points to an array or object, the original array or object is not changed. Instead, a new array or object is created and assigned to the variable.

    
      const myArray = [1, 2, 3];
      const newArray = myArray; // reassigning myArray to newArray
      newArray.push(4); // adding 4 to newArray
      
      console.log(myArray); // [1, 2, 3]
      console.log(newArray); // [1, 2, 3, 4]
    
  

Mutation

Mutation, on the other hand, is when you change the original array or object directly. When you mutate an array or object, you are modifying the original data structure in place.

    
      const myArray = [1, 2, 3];
      myArray.push(4); // mutating myArray by adding 4
      
      console.log(myArray); // [1, 2, 3, 4]
    
  

It’s important to be mindful of whether you want to reassign or mutate your arrays or objects in Javascript. Reassignment can be useful when you want to keep the original data intact, while mutation can be more efficient if you’re working with large data structures and want to avoid creating unnecessary copies.

0 0 votes
Article Rating
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@tusharsachdeva2481
7 months ago

indian tutorials are shit. i'll watch english ones from now on. they are just performing all the time. just fucking tell me the concept man

@mykhaylolytvynov5369
7 months ago

good explaining. You can continue this topic with clone object in js (shallow copy and deep copy)

@devtutsco
7 months ago

My first video back after a two-year hiatus 🎉! Appreciate any feedback on video or audio quality as well as requests for future videos.