# Creating new arrays or objects

It is not possible to directly make an array or object immutable in JavaScript. However, you can use specific methods to create a new copy of an array or object, which will preserve the value of the original variable.

To create a new copy of an array, you can use the following methods:

* The spread operator (`...`): This operator allows you to create a new array that includes the values of an existing array.

```javascript
const arr = [1, 2, 3];

const copy = [...arr];

console.log(copy); // [1, 2, 3]
```

The `Array.prototype.slice()` method: This method creates a new array that includes a copy of a portion of an existing array.

```javascript
const arr = [1, 2, 3];

const copy = arr.slice();

console.log(copy); // [1, 2, 3]
```

To create a new copy of an object, you can use the following methods:

* The `Object.assign()` method: This method creates a new object and copies the properties of an existing object into it.

```javascript
const obj = { name: 'John', age: 30 };

const copy = Object.assign({}, obj);

console.log(copy); // { name: 'John', age: 30 }
```

The spread operator (`...`): This operator can also be used to create a new object that includes the properties of an existing object.

```javascript
const obj = { name: 'John', age: 30 };

const copy = { ...obj };

console.log(copy); // { name: 'John', age: 30 }
```

Using these methods to create a new copy of an array or object allows you to preserve the value of the original variable, while still being able to modify the new copy if needed. This can be useful if you want to keep track of previous states of an array or object, or if you want to avoid unintended modifications to the original data.


---

# 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://demirels-organization.gitbook.io/javascript-tutorial/creating-new-arrays-or-objects.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.
