> For the complete documentation index, see [llms.txt](https://petercheng7788.gitbook.io/developer-note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://petercheng7788.gitbook.io/developer-note/programming-language/javascript/immutability.md).

# Immutability

## Primitive

* Primitives, like strings and numbers, are immutable by default

```javascript
let greet = "Hello";
greet += "World";  
console.log(greet); // Hello world
```

* Even if it is tried to be changed, new value with different memory address will be created instead of changing its original value

<figure><img src="/files/w6RI1SD3lUE3Z5ieBl2H" alt=""><figcaption></figcaption></figure>

* For function call , primitive input is immutable

```javascript
let test = "Hello";
const testFn = (input) => {
    test += "World";
}
testFn(test);
console.log(test) // Hello
```

## Array & Object

* Array and object are mutable

<pre class="language-javascript"><code class="lang-javascript"><strong>// Array
</strong><strong>let ages = [42, 22, 35];
</strong>ages.push(8);  
console.log(ages); // 42, 22, 35, 8

// Object
let p = {name:"Nee", age: 30};
p.age = 31;
console.log(p); // {name: "Nee", age:31}
</code></pre>

<figure><img src="/files/diOrClXvJnCbzljwzDV7" alt=""><figcaption></figcaption></figure>

* For function call , they are mutable

```javascript
let test = ["Hello"];
const testFn = (input) => {
    test.push("World");
}
testFn(test);
console.log(test) // [Hello, World]

let test2 = {key:"Hello"};
const testFn = (input) => {
    test2.key = "World";
}
console.log(test2); // {key: World}
```

* However, it is recommended to use immutable pattern for best practice to prevent from any side effect

```javascript
// Array
let test = ["Hello"];
test = [...test, "World"];
// Object
let p = {name:"Nee", age: 30};
p = {...p, age: 31};
console.log(p);
```
