Spread Operator

The spread operator is a very useful and concise way to use array operations such as adding elements to arrays, combining arrays (or objects), passing array parameters to functions, etc. We will learn together. details.

What is spread operator?

In Javascript, the spread operator refers to the use of the ellipsis symbol .... According to Javascript.info , the spread operator is defined as follows:

โ€œWhen ...arr is used in the function call, it โ€˜expandsโ€™ an iterable object arr into the list of arguments.โ€

Spread operator was added from ES6 version (ES2015), as well as rest parameter , these two types of operators are syntactically similar, that is, they use the same ....

So ...what is it used for?

โ€œSpread operator to the rescue! It looks similar to rest parameters, also using ..., but does quite the opposite.โ€ โ€” JavaScript.info

I will take the most basic example, which is the function to find the largest number in the array as follows:

Math.max(1,3,5) // output: 5
Math.max([1,3,5]) // output: NaN

When we pass an array of 3 elements as a parameter to a function (here the Math.max() function) as in line 2, we expect that the function will understand that we are passing in 3 separate parameters. difference, and find the largest number among these 3 numbers (as written in the 2nd line). Of course, if we write like that, the function will not be understood, and will output NaN. This is where we need ..., just add the sign ...to the argument section, we will get the desired result

Math.max(...[1,3,5]) // output: 5

In this case, the spread operator has expanded the 3-element array into 3 separate parameters.

In addition to the functions I mentioned above, the spread operator also has many other useful functions that help make our code much more concise and easier to see, such as:

  • Copy an array

  • Split or combine one or more arrays

  • Use an array as a list of arguments

  • Add an item to a list

  • Manipulating state in React

  • Combine objects

  • Convert NodeList into an array

Other examples of spread operators...

Next I will introduce to you a few examples that the spread operator can do such as copying arrays, splitting strings into characters, or combining properties of an object.

[...["๐Ÿ˜‹๐Ÿ˜›๐Ÿ˜œ๐Ÿคช๐Ÿ˜"]] // Array [ "๐Ÿ˜‹๐Ÿ˜›๐Ÿ˜œ๐Ÿคช๐Ÿ˜" ]
[..."๐Ÿ™‚๐Ÿ™ƒ๐Ÿ˜‰๐Ÿ˜Š๐Ÿ˜‡๐Ÿฅฐ๐Ÿ˜๐Ÿคฉ!"] // Array(9) [ "๐Ÿ™‚", "๐Ÿ™ƒ", "๐Ÿ˜‰", "๐Ÿ˜Š", "๐Ÿ˜‡", "๐Ÿฅฐ", "๐Ÿ˜", "๐Ÿคฉ", "!" ]

const hello = {hello: "๐Ÿ˜‹๐Ÿ˜›๐Ÿ˜œ๐Ÿคช๐Ÿ˜"}
const world = {world: "๐Ÿ™‚๐Ÿ™ƒ๐Ÿ˜‰๐Ÿ˜Š๐Ÿ˜‡๐Ÿฅฐ๐Ÿ˜๐Ÿคฉ!"}

const helloWorld = {...hello,...world}
console.log(helloWorld) // Object { hello: "๐Ÿ˜‹๐Ÿ˜›๐Ÿ˜œ๐Ÿคช๐Ÿ˜", world: "๐Ÿ™‚๐Ÿ™ƒ๐Ÿ˜‰๐Ÿ˜Š๐Ÿ˜‡๐Ÿฅฐ๐Ÿ˜๐Ÿคฉ!" }

Copy array

With the spread operator ..., we can copy the array in a very concise way, besides adding one or more elements to the array is also very easy:

const fruits = ['๐Ÿ','๐ŸŠ','๐ŸŒ','๐Ÿ‰','๐Ÿ']
//Copy the fruits array to the moreFruits array
const moreFruits = [...fruits]; 
console.log(moreFruits) // Array(5) [ "๐Ÿ", "๐ŸŠ", "๐ŸŒ", "๐Ÿ‰", "๐Ÿ" ]

Use array as list of parameters

โ€œThe Math object's set of functions are a perfect example of the spread operator as the only argument to a function.โ€ โ€” @davidwalshblog on his blog

One of the easiest ways to understand the use of the spread operator is class methods Math, here I will take the function Math.min()and Math.max()give an example. This function will find the smallest (or largest) number in the list of parameters we pass in. The number of parameters is arbitrary, this function only accepts a list of parameters, not an array. At this point we can use the spread operator:

const numbers = [37, -17, 7, 0]
console.log(Math.min(numbers)) // output is NaN because this function does not accept array as parameter

//Sแปญ dแปฅng spread operator
console.log(Math.min(...numbers)) // output: -17 
console.log(Math.max(...numbers)) // 37

Not only class functions Math, but all functions that receive an arbitrary number of parameters, we can use the spread operator. Let's take a few more examples:

const fruitStand = ['๐Ÿ','๐ŸŠ','๐ŸŒ']
const sellFruit = (f1, f2, f3) => { console.log(`Fruits for sale: ${f1}, ${f2}, ${f3}`) }
sellFruit(...fruitStand) // Fruits for sale: ๐Ÿ, ๐ŸŠ, ๐ŸŒ
fruitStand.pop()
fruitStand.pop()
fruitStand.push('๐Ÿ‰')
fruitStand.push('๐Ÿ')
sellFruit(...fruitStand) // Fruits for sale: ๐Ÿ, ๐Ÿ‰, ๐Ÿ
fruitStand.pop()
fruitStand.pop()
sellFruit(...fruitStand,'๐Ÿ‹') // Fruits for sale: ๐Ÿ, ๐Ÿ‹, undefined

Add elements to the array

As mentioned above, the spread operator can also add one or more elements to the array, making our code much simpler and more natural than the traditional way of writing code like before:

const fewFruit = ['๐Ÿ','๐ŸŠ','๐ŸŒ']
const fewMoreFruit = ['๐Ÿ‰', '๐Ÿ', ...fewFruit] //add the elements of array fewFruit to array fewMoreFruit
console.log(fewMoreFruit) //  Array(5) [ "๐Ÿ‰", "๐Ÿ", "๐Ÿ", "๐ŸŠ", "๐ŸŒ" ]

Manipulating state in React

When working with React, especially React Hooks, adding an element to React state will be done a lot easier, if we use .... Here is an example:

import React, { useState } from "react"
import ReactDOM from "react-dom"

import "./styles.css"

function App() {
  // Khai bรกo React Hook
  const [searches, setSearches] = useState([])
  const [query, setQuery] = useState("")

  const handleClick = () => {
     
    // Add an element to React Hook's state searches
    setSearches(searches => [...searches, query])
  }

Combine two or more objects together

The spread operator, in addition to being able to manipulate arrays, can also manipulate objects. We can use the spread operator to combine properties and methods of two or more objects into a new object. Here is an example:

const objectOne = {hello: "๐Ÿคช"}
const objectTwo = {world: "๐Ÿป"}

// Combine objectOne and objectTwo together in objectThree and add the laugh property
const objectThree = {...objectOne, ...objectTwo, laugh: "๐Ÿ˜‚"}
console.log(objectThree) // Object { hello: "๐Ÿคช", world: "๐Ÿป", laugh: "๐Ÿ˜‚" }

// Similarly we have objectFour, where laugh is a function
const objectFour = {...objectOne, ...objectTwo, laugh: () => {console.log("๐Ÿ˜‚".repeat(5))}}
objectFour.laugh() // ๐Ÿ˜‚๐Ÿ˜‚๐Ÿ˜‚๐Ÿ˜‚๐Ÿ˜‚

Some notes when using spread operator

There is an interesting thing that makes spread operators useful, which is that they will create a new reference, then copy the value of the old reference into this new reference. Then, any operation that changes the old reference will not affect the copied array, which would happen if we copied the array using the assignment method =,

const array = ['๐Ÿ˜‰','๐Ÿ˜Š','๐Ÿ˜‡']
const copyWithEquals = array // Changing the array array will also change the copyWithEquals array
const copyWithSpread = [...array] // Changing the array array will not affect the copyWithSpread array

array[0] = '๐Ÿ˜ก' //change the first element of array array

console.log(...array) // ๐Ÿ˜ก ๐Ÿ˜Š ๐Ÿ˜‡
console.log(...copyWithEquals) // ๐Ÿ˜ก ๐Ÿ˜Š ๐Ÿ˜‡
console.log(...copyWithSpread) // ๐Ÿ˜‰ ๐Ÿ˜Š ๐Ÿ˜‡

As you can see, due to the properties of the spread operator, copying an array has become more convenient, easier to control, and much less error-prone.

Conclude

Since its inception in ES6 (ES2015), the spread operator ...has been loved by the Javascript programming community because of its usefulness and brevity when manipulating arrays and objects. I myself often use it when working with React Hooks, especially when adding an element to the React state array.

Knowing new syntax will help us save time when coding, and also make our code much easier to read. And I hope this sharing of mine will help you in your arduous and difficult coding "career".

Last updated