Reading a bit of Javascript code, I've come across this:
router.route('/:id')
.put((...args) => controller.update(...args))
.get((...args) => controller.findById(...args));
Is anyone clear about what ... args means?
Reading a bit of Javascript code, I've come across this:
router.route('/:id')
.put((...args) => controller.update(...args))
.get((...args) => controller.findById(...args));
Is anyone clear about what ... args means?
As a colleague commented to your question, they are Parameters Rest , in where simply this ( ...args
) is an object of type array
ranging from 0
to args.length
, example:
function fun1(...args) {
console.log(args.length);
}
fun1(); // 0
fun1(5); // 1
fun1(5, 6, 7); // 3
Complementing what @Naos points out, the "ellipsis" are the Spread Operator , which allows you to specify that the function will treat what is contained in that parameter as an array, or more precisely an iterable one.
Formerly that was done using arguments
and in your question it would behave exactly the same: an array with all the parameters delivered to the function.
However, the spread operator also allows to do things that previously required an elaborate return by applying array_slice on arguments. For example, declare a function that you know its first parameter, but do not know all the rest:
function marcavehiculo(vehiculo, ...marcas) {
console.log('Quiero comprar un '+vehiculo+' de alguna de las siguentes marcas');
console.log(marcas);
}
marcavehiculo('automóvil','chevrolet','peugeot','citroen');
marcavehiculo('avión','boeing','airbus');