×
☰ See All Chapters

JavaScript ES6 Spread Operator

Spread operator consists of three dots (...). Using spread operator you can expand an array, an object or a string. Let us try to understand the usage of spread operator in different cases:

Expanding array

const x = [1, 2, 3];

const y = [...x, 4, 5, 6];

console.log(y);

Output:

 [1, 2, 3, 4, 5, 6]

Copying array

const x = [1, 2, 3];

const y = [...x];

console.log(y);

 

Output:

 [1, 2, 3]

Copying object

const box = {

    height: 10,

    width: 10,

    length: 10,

};

 

const clonedBox = {

    ...box

};

 

clonedBox.height = 20;

console.log(clonedBox);

Output:

 {height: 20, width: 10, length: 10}

Merging objects

const box = {

    height: 10,

    width: 10,

    length: 10,

};

const circle = {

    radius: 10

};

 

const elements = {

    ...box,

    ...circle

};

 

elements.radius = 20;

elements.length = 30;

console.log(elements);

Output:

{height: 10, width: 10, length: 30, radius: 20}

Converting String to character array

const message = 'Hello World';

const arrayized = [...message];

console.log(arrayized);

Output:

 ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

Using spread as function argument

const fun = (foo, bar) => {

        console.log(foo);

        console.log(bar);

};

const a = [1, 2];

fun(...a);

Output:

1

2

 


All Chapters
Author