ELI5 JavaScript: The Spread Operator
Tags: javascript, webdev, beginners, programming
Published: 2021-10-21 16:51:52

One of the most useful features introduced in ES6 is the Spread Operator. It is denoted by three dots (...).

According to MDN Web Docs:
> Spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

<center>
![Calculating Puzzled Gif](https://media.giphy.com/media/WRQBXSCnEFJIuxktnw/giphy.gif)
</center>

Sounds complex right?
Don't worry, read this article till the end, and I will make sure you know the ins and outs of the Spread Operator :)

<center>
![Let's Begin Gif](https://media.giphy.com/media/5zf2M4HgjjWszLd4a5/giphy.gif)
</center>

As the name suggests, the spread operator is used to 'spread' out the elements of an iterable (string, array, etc.). Let's look at an example:

```javascript
let arr = ["This", "is", "an", "array"]
console.log(arr) 
console.log(...arr) //with spread operator
``` 

```javascript
//output
["This", "is", "an", "array"]
This is an array
```

Okay! Now let's look at some use cases of the spread operator.

<h2>Table of Content</h2>

1. <a href="#passing-arguments">Passing arguments to functions</a>

2. <a href="#copying-arrays-objects">Copying arrays/objects</a>

    2.1 <a href="#copying-arrays">Arrays</a>
    2.2 <a href="#copying-objects">Objects</a> 

3. <a href="#combining-arrays-objects">Combining arrays/objects</a>

    3.1 <a href="#combining-arrays">Arrays</a>
    3.2 <a href="#combining-objects">Objects</a> 

4. <a href="#string-to-characters">String to characters</a>

<h3 id="passing-arguments">1. Passing arguments to functions</h3>

```javascript 
let num = [1, 2, 3 ,4]
console.log(Math.min(num[0], num[1], num[2], num[3]))
```

Instead of passing each element separately, you can use the spread operator! 

```javascript 
console.log(Math.min(...num))
```

<h3 id="copying-arrays-objects">2. Copying arrays/objects</h3>

Use the spread operator to create copies of arrays & objects.

<h4 id="copying-arrays">2.1 Arrays</h4>

```javascript 
let arr1=["a", "b", "c", "d"]
let arr2 = arr1 
let arr3 = [...arr1]
arr1.push("e")
console.log("arr1 = ", arr1)
console.log("arr2 = ", arr2)
console.log("arr3 = ", arr3)
```

Can you guess the output?

```javascript 
//output 
"arr1 = " ["a", "b", "c", "d", "e"]
"arr2 = " ["a", "b", "c", "d", "e"]
"arr3 = " ["a", "b", "c", "d"]
```

Let's understand what happened...
- The assignment operator (=) creates a reference to the original array. So here,
arr2 is just a reference to arr1. Both arr1 and arr2 point to the same array in memory!
- To make a copy, we use the spread operator! By using the spread operator we make a new copy of the array in the memory. Now changes made to arr1 will not be reflected in arr3 (and vice-versa)

<h4 id="copying-objects">2.2 Objects</h4>

```javascript
let obj1 = {
    firstName: "Nisarg",
    lastName: "Kapkar",
    website: "Hashnode",
    twitter: "@nnkkaapp"
}
let obj2 = obj1 
let obj3 = {...obj1}
obj1.website = "Medium"
```

Similar to arrays, changing obj1 changes obj2 but not obj3.

**NOTE:
While copying arrays/objects, the spread operator only goes one level deep.**

```javascript 
let num1 = [[1, 2], [3, 4], [5, 6]]
let num2 = [...num1]
num1[0][0] = 100
console.log(num1)
console.log(num2)
```

Here, both num1 and num2 will be equal to [[100, 2], [3, 4], [5,6]]. 
A similar thing happens when you copy nested objects using the spread operator.
The nested arrays/objects inside an array/object are just references. So when you use the spread operator to copy, the nested arrays/objects are not copied (rather their references are copied)

<h3 id="combining-arrays-objects">3. Combining arrays/objects</h3>

Use the spread operator to combine arrays & objects (and insert elements in arrays & objects)

<h4 id="combining-arrays">3.1 Arrays</h4>

```javascript 
let arr1 = [1, 2, 3, 4]
let arr2 = [4, 5, 6]
let arr3 = [...arr1, 7, ...arr2, 8]
console.log(arr3)
```
arr3 will contain 1, 2, 3, 4, 7, 4, 5, 6, 8 (arr1 elements+7+arr2 elements+8)

<h4 id="combining-objects">3.2 Objects</h4>

```javascript
let obj1 = {
    firstName: "Nisarg",
    lastName: "Kapkar",
    website: "Hashnode"
}
let obj2 = {
    twitter: "@nnkkaapp",
    website: "Medium"
}
let obj3 = {...obj1, ...obj2, dob: "23/12/2000"}
console.log(obj3)
```

```javascript
//output
{
    firstName: "Nisarg",
    lastName: "Kapkar",
    website: "Medium",
    twitter: "@nnkkaapp",
    dob: "23/12/2000"
}
```

**NOTE:
If there are multiple values for the same key (in the above example: 'website'), the last encountered value is assigned, and all the previous values are overwritten (in the above example, 'Hashnode' is overwritten by 'Medium')**

<h3 id="string-to-characters">4. String to characters</h3>

```javascript 
let firstName = "Nisarg" 
console.log([...firstName])
```

Since a string is iterable, we can use the spread operator on it. The output of above code will be ["N", "i", "s", "a", "r", "g"]

<hr>

Woooo! Thank you for reading 😄

<center>
![wooo Gif](https://media.giphy.com/media/2E6OYt2yphlWTGZeYK/giphy.gif)
</center>

If you have any questions about the Spread Operator (or about JavaScript in general), feel free to ask them in the comments 👇

<hr>

This article is part of my ELI5 JavaScript series.
If you want to read & learn more about JavaScript, don't forget to subscribe (more articles coming soon!)

Follow me 👇 for more content on full-stack development, software engineering & data structures/algorithms.

- <a href="https://twitter.com/nnkkaapp">Twitter</a>
- <a href="https://www.linkedin.com/in/nisarg-kapkar/">Linkedin</a>
- <a href="https://github.com/Nkap23">Github</a>

Thank you again :)
Have an awesome day and happy coding 😄