i2tutorials

Javascript-Spread Syntax

Javascript-Spread Syntax

 

This operator allows an iterable to expand in places from 0+ arguments are expected. It is mostly using a variable array where there is more than 1 value is expected. It allows the privilege to obtain a list of parameters from a variable array. Syntax of Spread operator is the equal as Rest parameter but it works completely opposite of it.

 

Syntax:

 

var variablename1 = [...value];

 

Spread operators can be provided in different cases, like when we want to expand, copy,concat, with math objects.

 

Concat():

 

merge two or more arrays.

 

// normal array concat() method
let arr = [1,2,3];
let arr2 = [4,5];

arr = arr.concat(arr2);

console.log(arr); // [ 1, 2, 3, 4, 5 ]

 

Javascript-Spread Syntax

 

Copy:

 

copy the content of array to another .

 

// copying without the spread operator
let arr = ['a','b','c'];
let arr2 = arr;

console.log(arr2); // [ 'a', 'b', 'c' ]

 

 

Expand:

 

expand an array into another.

 

// normally used expand method
let arr = ['a','b'];
let arr2 = [arr,'c','d'];

console.log(arr2); // [ [ 'a', 'b' ], 'c', 'd' ]

 

 

Example of spread operator:

 

The spread operator (…) with objects is used to return copies of existing objects with new/updated values or to make a copy of an object with more properties.

 

const user1 = {
       name: 'Jen',
       age: 22
};

const clonedUser = { ...user1 };
console.log(clonedUser);

 

 

 

 

 

 

 

Exit mobile version