Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of "...args" (three dots) in a function definition?

It was really confusing for me to read this syntax in Javascript:

router.route('/:id') .put((...args) => controller.update(...args)) .get((...args) => controller.findById(...args)); 

What does ...args mean?

like image 294
Cesar Jr Rodriguez Avatar asked Feb 12 '17 05:02

Cesar Jr Rodriguez


People also ask

What is the meaning of 3 dots in java?

The "Three Dots" in java is called the Variable Arguments or varargs. It allows the method to accept zero or multiple arguments. Varargs are very helpful if you don't know how many arguments you will have to pass in the method.

What is the meaning of args?

Usually, ... args means "any number of values". For example, you could pass null or 1,2,3,4 - it would not matter and the method is smart enough to deal with it.

What are args in code?

The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key worded, variable-length argument list.

What does args mean in Python?

Python has *args which allow us to pass the variable number of non keyword arguments to function. In the function, we should use an asterisk * before the parameter name to pass variable length arguments.


2 Answers

With respect to (...args) =>, ...args is a rest parameter. It always has to be the last entry in the parameter list and it will be assigned an array that contains all arguments that haven't been assigned to previous parameters.

It's basically the replacement for the arguments object. Instead of writing

function max() {   var values = Array.prototype.slice.call(arguments, 0);   // ... } max(1,2,3); 

you can write

function max(...value) {   // ... } max(1,2,3); 

Also, since arrow functions don't have an arguments object, this is the only way to create variadic (arrow) functions.


As controller.update(...args), see What is the meaning of "foo(...arg)" (three dots in a function call)? .

like image 86
Felix Kling Avatar answered Sep 18 '22 17:09

Felix Kling


Essentially, what's being done is this:

.put((a, b, c) => controller.update(a, b, c)) 

Of course, what if we want 4 parameters, or 5, or 6? We don't want to write a new version of the function for all possible quantities of parameters.

The spread operator (...) allows us to accept a variable number of arguments and store them in an array. We then use the spread operator again to pass them to the update function:

.put((...args) => controller.update(...args)) 

This is transparent to the update function, who receives them as normal arguments.

like image 34
bejado Avatar answered Sep 21 '22 17:09

bejado