I know one has to be very careful with the function Arguments object
But are there any known downsides (optimization/performance issues) to using the spread syntax with the Arguments object? Or is this totally okay?
I want to create an array from an unknown amount of arguments passed to a function:
function Numbers(){
this.numbers = [...arguments];
}
A fiddle can be found here
It looks quite neat, and in the MDN page about the Arguments object is even suggested that I can use spread syntax for this:
As you can do with any Array-like object, you can use ES2015's
Array.from()
method or spread syntax to convertarguments
to a real Array
But I still would like see if others have another opinion on this.
Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list.
To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables. Syntax: function_name(object_name); Example: In this Example there is a class which has an integer variable 'a' and a function 'add' which takes an object as argument.
The spread operator … is useful for working with arrays and objects in JavaScript. It is a convenient feature added in ES6 (ES2015).
You can also use rest parameters:
function Numbers(...numbers){
this.numbers = numbers;
}
Using a spread does the same thing cleaner in ES2015
this.numbers = [...arguments];
Just remember that this won't work in arrow functions (no arguments
), and you're good. Rest arguments and Array.from are other options that are fine as well.
The old-fashioned ES5 is:
this.numbers = [].slice.call(arguments);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With