Three dots ( … ) in JavaScript

Sagar Gavhane on September 15, 2018

Hey! I'm Sagar. I love to write tutorials and articles to help developers better understand the magic of JavaScript. If you have any questions abo... [Read Full]
markdown guide
 

Hi I noticed that the Shallow-cloning isn't working in Edge (18)

var obj1 = { foo: 'bar', x: 42 };
var obj2 = { foo: 'baz', y: 13 };

var clonedObj = { ...obj1 };

Result: error in console 'Expected identifier, string or number'
 

Great explanation! I knew about the rest parameters and even used them in my code, and now, thanks to your explanation, I will also use the spread operator. First of all, I replace all Object.assign() in my code with a short form.

 
 

Great article! This was a really great explanation of spread/rest.

I'd also add that three dots on the left-side of an equals sign is "destructuring assignment" and allows you to "pull out" values.

ex:

[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(rest); // [30,40,50]

let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
console.log(a); // 10 
console.log(b); // 20 
console.log(rest); // { c: 30, d: 40 }
 
 

Wonderful explanations, I've found this to be one of the more confusing elements of new JS.

 

Me too, it seems to promote a „many positional arguments“ programming style instead of composing things into useful objects 🤔 Also the destructuring on the method definition is a part of this thing... i think

 

Yes, Ben I found three dot operator confuse when use try to us in project. Thanks for your feedback.

 

The other usage of ... I found is very useful:

Converting an iterable object:

// An array of HTMLElement, not the annoying NodeList object
const array = [...document.querySelectorAll('div')]; 

Event a generator, how cool is that?

const array = [...(function*() {
  for (let i = 10; i > 0; i--) {
    yield i;
  }
  yield 'Launch';
})()];

console.log(array);    // [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, "Launch"]
 

Thanks for the great explanation Sagar, rest/spread basically performs the exact same job as the "splat operator" in php.

 

It's important to note that this feature is available in all major browsers except for IE11

caniuse.com/#feat=rest-parameters

 
 
 
 
 
code of conduct - report abuse