Forward Thinking — a never-complete guide to modern JavaScript #4 Spread Operator

Tomasz Zwierzchoń
Nov 13, 2017 · 2 min read

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.

Orba

We create and develop B2B & B2C e-commerce systems

Orba

We create and develop B2B & B2C e-commerce systems

Tomasz Zwierzchoń

Written by

IT Architect. FrontEnd Team Lead. #JavaScript on #IoT #UX #Vue.js Fan. I miss having free time, especially for dancing Tango.

Orba

We create and develop B2B & B2C e-commerce systems