The spread operator (...) in JavaScript is used to expand or spread elements of an iterable (like an array or a string) into individual elements. It can be used in various contexts, such as:
-
Array Literals: To create a new array by combining existing arrays or adding new elements.
const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const combinedArray = [...array1, ...array2]; // [1, 2, 3, 4, 5, 6] -
Function Arguments: To pass elements of an array as individual arguments to a function.
const numbers = [1, 2, 3]; const sum = (a, b, c) => a + b + c; console.log(sum(...numbers)); // 6 -
Object Literals: To create a new object by copying properties from an existing object.
const obj1 = { a: 1, b: 2 }; const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 } -
String Expansion: To convert a string into an array of characters.
const str = "hello"; const chars = [...str]; // ['h', 'e', 'l', 'l', 'o']
The spread operator is a powerful feature that simplifies code and enhances readability.
