Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using spread syntax with function Arguments object

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 convert arguments to a real Array

But I still would like see if others have another opinion on this.

like image 319
Wilt Avatar asked Sep 29 '16 15:09

Wilt


People also ask

Can you use the spread operator on an object?

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.

How do you pass an argument to an object?

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.

Does spread operator work on objects JavaScript?

The spread operator … is useful for working with arrays and objects in JavaScript. It is a convenient feature added in ES6 (ES2015).


2 Answers

You can also use rest parameters:

function Numbers(...numbers){
    this.numbers = numbers;
}
like image 157
madox2 Avatar answered Sep 22 '22 08:09

madox2


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);
like image 22
adeneo Avatar answered Sep 21 '22 08:09

adeneo