The spread operator in JavaScript, denoted by three dots ..., is a versatile feature introduced in ES6 (ECMAScript 2015) that allows the expansion of iterable objects into individual elements or the merging of objects and arrays. It's used in various contexts for different purposes:
-
Array Manipulation:
Spread in Array Literals:
const array1 = [1, 2, 3]; const array2 = [...array1, 4, 5]; // Creates a new array by spreading elements of array1 console.log(array2); // Output: [1, 2, 3, 4, 5]
Concatenating Arrays:
const array1 = [1, 2, 3]; const array2 = [4, 5]; const concatenatedArray = [...array1, ...array2]; // Concatenates arrays using spread console.log(concatenatedArray); // Output: [1, 2, 3, 4, 5]
Copying Arrays:
const originalArray = [1, 2, 3]; const copiedArray = [...originalArray]; // Creates a shallow copy of the array
-
Object Manipulation:
Copying Objects (Shallow Merge):
const obj1 = { a: 1, b: 2 }; const obj2 = { ...obj1, c: 3 }; // Copies obj1 properties and adds a new property console.log(obj2); // Output: { a: 1, b: 2, c: 3 }
Merging Objects:
const obj1 = { a: 1, b: 2 }; const obj2 = { c: 3, d: 4 }; const mergedObject = { ...obj1, ...obj2 }; // Merges properties of obj1 and obj2 console.log(mergedObject); // Output: { a: 1, b: 2, c: 3, d: 4 }
-
Function Arguments:
Passing Array Elements as Arguments:
function sum(a, b, c) { return a + b + c; } const numbers = [1, 2, 3]; const result = sum(...numbers); // Passes elements of numbers as individual arguments console.log(result); // Output: 6
-
Strings:
Converting Strings to Arrays:
const str = 'hello'; const chars = [...str]; // Converts string into an array of characters console.log(chars); // Output: ['h', 'e', 'l', 'l', 'o']
In summary, the spread operator simplifies tasks like copying, merging, and expanding iterable objects (arrays, objects, strings) in JavaScript, providing a concise and powerful syntax.