JavaScript Spread Operator

The Spread operator (…) allows an iterable such as an array, map, or set to be expanded in places where zero plus arguments or elements are expected.

The spread syntax is the same as the rest syntax, but the spread syntax works opposite.

Syntax

let variable_name = [...value]; 

Example 1: How to Use Spread Operator

Visual Representation

Visual Representation of JavaScript Spread Operator

let arr = [11, 21];

let combined = [...arr, 19, 33];

console.log(combined);

Output

[ 11, 21, 19, 33 ]

Example 2: Copying an Array 

Create a shallow copy of an array.

Visual Representation

Visual Representation of Copying an Array

const original = [11, 21, 19];
const copy = [...original];

console.log(copy); 

Output

[ 11, 21, 19 ]

Example 3: Concatenating or Merging Arrays

Visual Representation

Visual Representation of Concatenating or Merging Arrays

let arr1 = [11, 21, 19];
let arr2 = [18, 10, 46]

let concatenated = [...arr1, ...arr2]
console.log(concatenated);

Output

[ 11, 21, 19, 18, 10, 46 ]

Example 4: Object Literal Expressions to Copy or Merge Objects

Javascript objects spread syntax allows you to do the equivalent of Object.assign(), copying the values of an object into a new one.

const obj = {
  name: 'AppDividend',
  author: 'Krunal Lathiya'
};

const combined = {
  ...obj,
  age: 30
};

console.log(combined);

Output

{ name: 'AppDividend', author: 'Krunal Lathiya', age: 30 }

Example 5: Function Arguments

function multiplication(x, y, z) {
  return x * y * z;
};

const args = [5, 10, 15];
const output = multiplication(...args);

console.log(output);

Output

750

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.