Javascript / Typescript rest and spread operators
To make it easier, rest and spread operator basically helps to merge all your function parameter together. In the past, we use something like
myfunction.apply(null, myAgumentList)
With rest and spread we can easily
function log(...a) {
console.log(a);
}
log(1,2,3,4,5); // outputs [1, 2, 3, 4, 5] array
Notice we're assigning myArguments at the back.
let myArguments = ['x', 'y', 3]
log(1,2, myArguments); // outputs [1, 2, ['x', 'y', 3]] 2 different array
log(1,2, ...myArguments); // outputs [1, 2, 'x', 'y', 3] 1 array
Notice we're assigning myArguments at the front.
log(...myArguments,1,2 ); // outputs [ 'x', 'y', 3, 1, 2] essentially a single array.
myfunction.apply(null, myAgumentList)
With rest and spread we can easily
function log(...a) {
console.log(a);
}
log(1,2,3,4,5); // outputs [1, 2, 3, 4, 5] array
Notice we're assigning myArguments at the back.
let myArguments = ['x', 'y', 3]
log(1,2, myArguments); // outputs [1, 2, ['x', 'y', 3]] 2 different array
log(1,2, ...myArguments); // outputs [1, 2, 'x', 'y', 3] 1 array
Notice we're assigning myArguments at the front.
log(...myArguments,1,2 ); // outputs [ 'x', 'y', 3, 1, 2] essentially a single array.
Comments