Forward Thinking — a never-complete guide to modern JavaScript #4 Spread Operator
In the previous post we’ve met magic three dots „…” alias spread operator. Those dots are worth exploring before we will go to maps.
Main objective of the spread operator is to spread the elements of an array or an iterable object.
Try this code:
const log = x => console.log(x);
const myFunction = (a, b, c) => {
log(`a: ${a}, b: ${b}, c: ${c}`)
};
const myArr1 = [1, 2, 3];myFunction(...myArr1);
As you can see each element in the array is passed as the argument to the function. But we can do more! A few examples below.
Any argument in the list can use spread syntax:
const log = x => console.log(x);
const myFunction = (a, b, c) => {
log(`a: ${a}, b: ${b}, c: ${c}`)
};
const myArr2 = [1, 2];myFunction(...myArr2,69);
Coping one array to the second or combining them:
const log = x => console.log(x);
const myArr3 = ['Lorem', 'Ipsum', 'Sit', 'Amet'];const myArr4 = [...myArr3];
log(myArr4);const myArr5 = [2, 3, 5, 7, 11, ...myArr3];
log(myArr5);myArr5.unshift(...myArr3);
log(myArr5);
Or we can use it to deconstructions:
const log = x => console.log(x);
const [a, b, ...rest] = [1, 2, 3, 4, 5, 6, 7];
log(`a: ${a}, b: ${b}, rest: ${rest}`);
I hope you will like those dots as much as I do.