JavaScript Spread Operator Tutorial

In this section, we will learn what the spread operator is and how to use it in JavaScript.

Note: we’re assuming you’re familiar with the iterator design pattern.

What is Spread Operator in JavaScript?

The spread operator, as the name suggest will spread the elements of an iterable object. Basically, when we run the spread operator on an iterable object, all the elements of that object will return. It’s somewhat similar to the `for of` loop.

To apply the spread operator on an iterable object, all we need to do is to put an ellipsis on the left side of an iterable object.

For example, we know that an array is iterable. So if we put an ellipsis on the left side of the name of an array, all the elements of that array will return.

Example: using spread operator in JavaScript

const arr = ["John","Doe"];

console.log(...arr);

Output: John Doe

Use case of JavaScript Spread Operators

There are many use cases for the spread operator. For example, via this operator, we can copy the content of one iterable object and pass it as the elements of an array.

Example: using spread operator to take the elements of an iterable object

const obj = {
  [Symbol.iterator](){
    let counter = 0;
    return {
      next(){
        counter++; 
        if (counter ==1){
          return {value:"One", done: false};
        }
        if (counter ==2){
          return {value: "Two", done: false};
        }
        if (counter ==3){
          return {value: "Three", done: false};
        }
        return {value: undefined, done: true};
      }
    }
  }
}
const arr = [...obj];
console.log(...arr);

Output:

One Two Three

Example: JavaScript spread operator and generators

function * generator(){
  yield "One";
  yield "Two";
  yield "Three";
}
const arr = [...generator()];
console.log(...arr);

Output:

One Two Three

Example: Copying arrays using JavaScript spread operator

Note: considering the fact that arrays are also iterable, we can apply the spread operator on an array to copy its content and pass it to another array.

const arr = [1,2,3,4,5,56,7,8,5,4,3,24];
const arr2 = [...arr];
console.log(...arr2);

Output:

1 2 3 4 5 56 7 8 5 4 3 24

Example: spread operator and function arguments in JavaScript

Also via the spread operator we can pass the elements of an iterable object as the argument to a function.

const arr = ["John","Doe"];
function sayHi(firstName , lastName){
  console.log(`Hello ${firstName} ${lastName}`);
}
sayHi(...arr);

Output:

Hello John Doe

So here the first element of the array will be assigned as the value of the `firstName` parameter and the second element of the array will be assigned as the value of the `lastName` parameter of the `sayHi()` function.

Leave a Reply