ES6 introduced “…” operator which is also called as spread operator. When “…” operator is applied on an array it expands the array into multiple variables in syntax wise. And when its applied to an function argument it makes the function argument behave like array of arguments.
We can use spread operator to take indefinite number of arguments.
Here is an example code of how to use this operator
function function_one(...args)
{
console.log(args);
console.log(args.length);
}
function_one(1, 4);
function_one(1, 4, 7);
function_one(1, 4, 7, 0);
function function_two(a, b, ...args)
{
console.log(args);
console.log(args.length);
}
//"args" holds only 7 and 9
function_two(1, 5, 7, 9);
Before ES6 introduced “…” operator developers used Array.prototype.slice.call
to retrieve the extra passed arguments.
Here is an example code:
function function_one()
{
var args = Array.prototype.slice.call(arguments, function_one.length);
console.log(args);
console.log(args.length);
}
function_one(1, 4);
function_one(1, 4, 7);
function_one(1, 4, 7, 0);
function function_two(a, b)
{
var args = Array.prototype.slice.call(arguments, function_two.length);
console.log(args);
console.log(args.length);
}
//"args" holds only 7 and 9
function_two(1, 5, 7, 9);
If we apply “…” to an array it expands it into multiple variables syntax wise. Here is an example code
{
console.log(a+b);
}
var array = [1, 4];
function_name(...array); //is equal to function_name(1, 4)