# 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);
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://petercheng7788.gitbook.io/developer-note/programming-language/javascript/immutability.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
