'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?



Solution 1:[1]

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.

Solution 2:[2]

The meaning of “…args” (three dots) is Javascript spread operator.

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// expected output: 6

Solution 3:[3]

If you know some Python syntaxes, it is exactly the same as *args. Since *args (Python) is tuple object and Javascript has no tuple like Python, ..args is an Array object.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bejado
Solution 2
Solution 3 Éofèq