Hacker News new | ask | show | jobs
by limsup 4245 days ago
Can someone explain what the "spread operator" is and how to use it?
3 comments

Spread is like python's *args.

Instead of this:

  var mapArgs = function() {
    var args = Array.prototype.slice.call(arguments, 0, arguments.length - 1);
    var mapper = Array.prototype.slice.call(arguments, arguments.length - 1);
    return args.map(mapper);
  };
You can do this:

  var mapArgs = function(...args, mapper) {
    return args.map(mapper);
  };
And you can also use it to apply. Instead of:

  var max = Math.max.apply(null, [1, 2, 3, 4]);
You can do:

  var max = Math.max(...[1, 2, 3, 4]);
heydenberk explained it well, but just to add some clarity on why you'd want to use prototype.apply for array as an argument -

http://stackoverflow.com/questions/2856059/passing-an-array-...

http://stackoverflow.com/questions/1316371/converting-a-java...

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

I'm still learning more about JS and so I'm no expert, but it seems to be similar in concept to use the ... in other languages. I think Groovy has something similar and Java has the varargs. They have obvious differences, but conceptually I think of it as passing in a variable number of args.

Wow, the example in that gist:

  var component = <Component {...props} foo={'override'} />;
Wha?? For me, there's a point in a language where the benefits of syntactic sugar are outweighed by readability concerns.