10

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.

4 Answers 4

9

You can also use rest parameters:

function Numbers(...numbers){
    this.numbers = numbers;
}
Sign up to request clarification or add additional context in comments.

Comments

3

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);

Comments

2

It's fine to use spread notation (it's not an operator) with arguments. Or at least, it's as fine as it ever is to use arguments. In ES2015 and above (e.g., if you have spread notation), there's very limited call to use arguments.

And indeed, there's no need in your example: Use rest arguments:

function Numbers(...args){
    this.numbers = args;
}

In that example, args is an array. A true array.

1 Comment

Nice, didn't know I could do that too :)
0

One reason people say not to use the arguments object is because it looks like an array but its not:

The arguments object is not an Array. It is similar to an Array, but does not have any Array properties except length. For example, it does not have the pop method. However it can be converted to a real Array:

You're good to go here because, like Array.from() the spread operator makes a new copy

1 Comment

That's one reason. There's also a performance impact in loose mode, and arrow functions don't have their own arguments object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.