# Immutability

#### Immutability[​](https://redux.js.org/tutorials/essentials/part-1-overview-concepts#immutability) <a href="#immutability" id="immutability"></a>

"Mutable" means "changeable". If something is "immutable", it can never be changed.

JavaScript objects and arrays are all mutable by default. If I create an object, I can change the contents of its fields. If I create an array, I can change the contents as well:

```
const obj = { a: 1, b: 2 }
// still the same object outside, but the contents have changed
obj.b = 3
const arr = ['a', 'b']
// In the same way, we can change the contents of this array
arr.push('c')
arr[1] = 'd'
```

This is called _<mark style="color:purple;">mutating</mark>_ the object or array. It's the same <mark style="color:orange;">object or array reference</mark> in memory, but now the contents inside the object have changed.

**In order to update values immutably, your code must&#x20;**<mark style="color:purple;">**make**</mark><mark style="color:purple;">**&#x20;**</mark>_<mark style="color:purple;">**copies**</mark>_<mark style="color:purple;">**&#x20;**</mark><mark style="color:purple;">**of existing objects/arrays, and then modify the copies**</mark>.

We can do this by hand using JavaScript's array / object spread operators, as well as array methods that return new copies of the array instead of mutating the original array:

```javascript
const obj = {  
    a: {    
        // To safely update obj.a.c, we have to copy each piece
        c: 3  
    },  
    b: 2
}
const obj2 = {
  // copy obj  
  ...obj,  
  // overwrite a  
  a: {
      // copy obj.a    
      ...obj.a,
      // overwrite c    
      c: 42  
  }
}

const arr = ['a', 'b'];
// Create a new copy of arr, with "c" appended to the end
const arr2 = arr.concat('c');
// or, we can make a copy of the original array:
const arr3 = arr.slice();
// and mutate the copy:
arr3.push('c');
```

