What Does ... (Three Dots) Mean In JavaScript

What Does … (Three Dots) Mean In JavaScript

In this tutorial, you’ll learn what  ( three dots ) mean in JavaScript. Three Dots (…) which are know as Spread or Rest operator in JavaScript were introduced as an ES6 feature. Let’s first try to understand how three dots work as Spread operator in JavaScript.

Spread Operator In JavaScript

As the word Spread suggests the three dots (…) can be used to spread the contents on an array.

let arr = [1, 2, 3, 4]
console.log(...arr)

Output : 1,2,3,4

There might be methods which may be accepting a list of items instead of an array. At this point Spread operator comes in handy and can be used to convert an array to a spread out list.

/*
* getParams accepts a list of parameters
*/
function getParams(a, b, c){
  console.log(a.name);
  console.log(b.age);
  console.log(c.city);
}

let param = [
  {'name' : 'James'},
  {'age' : 30},
  {'city' : 'Delhi'}
];

getParams(...param);

Outputs : 
  James
  30
  Delhi

Rest Operator In JavaScript

It does the exact opposite of what a Spread operator does. It combines the spread out elements into a single array.

/*
* getParams accepts a single array of params
*/
function getParams(paramArr){
    console.log(paramArr)
}

let params = '123'

getParams([...params]);

Outputs : ["1", "2", "3"]

Conclusion

In this tutorial, you learnt what three dots (…) mean in JavaScript. Three dots (…) in JavaScript can be used as Spread operator and Rest operator.

Leave a Reply

Your email address will not be published. Required fields are marked *