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
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
const original = [11, 21, 19];
const copy = [...original];
console.log(copy);
Output
[ 11, 21, 19 ]
Example 3: Concatenating or Merging Arrays
Visual Representation
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
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.