I am looking at a open source javascript application, specifically an extension for firefox.
I am seeing this syntax in multiple places that I do not know what it means if anyone can shed some light on this.
such as..
return (...args)
or...
console.info(message, ...args.slice(1));
any idea what this '...' does? Is it like getting the third argument in or what? Third argument back? Its hard to try and debug this without being able to understand it.
I am looking at a open source javascript application, specifically an extension for firefox.
I am seeing this syntax in multiple places that I do not know what it means if anyone can shed some light on this.
such as..
return (...args)
or...
console.info(message, ...args.slice(1));
any idea what this '...' does? Is it like getting the third argument in or what? Third argument back? Its hard to try and debug this without being able to understand it.
Share Improve this question asked Feb 9, 2015 at 23:23 tnedutstneduts 1151 silver badge6 bronze badges 1- 2 It's the Spread operator. Similar to it, but for use with named function parameters, is the Rest operator. – Jonathan Lonowski Commented Feb 9, 2015 at 23:26
3 Answers
Reset to default 8It will unpack an array (args) into a formal argument list. Amongst other things this allows the members of a rest parameter to be passed as a set of formal arguments to another function.
Here's an example:
var stats = function(...numbers) {
for (var i=0, total = 0, len=numbers.length; i<len; i++) {
total += numbers[i];
}
return {
average: total / arguments.length,
max: Math.max(numbers); //spread array into formal params
}
}
stats(5, 6, 8, 5); //{average: 6, max: 8}
Hope this help you understand "..."!
It's an Ecmascript 6 "rest" parameter. When used as a parameter or argument, it lets you receive or pass an array as individual arguments.
http://ariya.ofilabs./2013/03/es6-and-rest-parameter.html
The three periods after the final parameter's type (before parameter's name) indicate that the final argument may be passed as an array or as a sequence of arguments. Varargs can be used only in the final argument position(static)