DEV Community

Suggestions for using `...arguments` while working with functions in javascript.

Gokul Kathirvel on April 06, 2018

In many situations, using arguments to pass the function args would lead to bugs as we totally unaware the actual args. When to use these such notations and when not to?

Collapse
 
nektro profile image
Meghan (she/her)

First note, try not to use arguments as it was reserved in the past and not allowed in strict mode anymore.

Also are you referring to function_call(...args); or function call_me(...args) {}?

Collapse
 
gokatz profile image
Gokul Kathirvel

function_call(...args)

Collapse
 
nektro profile image
Meghan (she/her)

That is a type of array destructuring and can be used to pass the elements of an array to a function.

const array = [ 4, 2 ];
const sixteen = Math.pow(...array);

is equivalent to

const sixteen = Math.pow(4, 2);
// or
const sixteen = Math.pow(array[0], array[1], /* ... */);
Thread Thread
 
gokatz profile image
Gokul Kathirvel

yeah, but in a component model, when handling functions, it becomes black box

passToAnotherFunc() {
  handleItSomewhere(...arguments);
}

now, I completely unaware of the argument list!

Thread Thread
 
nektro profile image
Meghan (she/her)

the value of arguments here is the value of the arguments passed to passToAnotherFunc. See the deprecated arguments object

Thread Thread
 
antjanus profile image
Antonin J. (they/them)

Wait, the arguments isn't deprecated, it's only arguments.caller property that's non-standard and deprecated.

Thread Thread
 
shalvah profile image
Shalvah • Edited

Combining Meghan's two earlier responses, a better way would be:

passToAnotherFunc(...args) {
  handleItSomewhere(...args);
}

But I feel it's unlikely you'd need to write this kind of code. Could you give a real-world example?

Thread Thread
 
nektro profile image
Meghan (she/her)

@antjanus it's not deprecated per-se but it is disabled in strict and module mode.

@shalvah +1 because instead of calling passToAnotherFunc to call handleItSomewhere, why not just call handleItSomewhere?

Thread Thread
 
antjanus profile image
Antonin J. (they/them)

I had no idea it was disabled in strict/module mode!

Collapse
 
aralroca profile image
Aral Roca

Is useful, for example, if doesn't matter how many parameters receive the function:

const sum = (...numbers) => numbers.reduce((a, b) => a + b, 0);

sum(1, 4); // 5
sum(2, 3, 4); // 9
Collapse
 
nateous profile image
Nate

Generally speaking you should only use it if you were writing some library i guess. Most of the time i just use it for debugging. But you're right that it would probably be buggy in most cases.