2

I just started learn Javascript, I'm confused about the function parameter ...[1,2], why the function parameter like this.

function compare(a, b) {
    return a - b;
}
let result = compare(...[1,2]);
console.log(result);
user2864740
  • 60,010
  • 15
  • 145
  • 220
Jack
  • 5,540
  • 13
  • 65
  • 113
  • 3
    It's called the spread operator. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax – FThompson Jan 13 '19 at 03:18
  • 2
    Although it's worth mentioning that in this particular case it's a poor use, since the function itself won't actually handle more than two arguments. – Paul Jan 13 '19 at 03:21
  • It called spread operator. But in this sample code I think we don't need to do this. since your `compare` function only need two parameters (Assume this is real code). – Hoang Subin Jan 13 '19 at 04:25

1 Answers1

1

It's a new Es6 functionality called the spread operator, it's great for calling functions (without apply), converting arguments or NodeList to Arrays, array manipulations, and even when using the Math functions.

https://davidwalsh.name/spread-operator