JavaScript(JS) Spread Operator
The spread operator (...
) in JavaScript is a syntax for spreading the elements of an iterable (like an array or a string) into individual elements. It can be used in a variety of contexts to make working with iterable data structures more flexible and expressive.
Here are some examples of using the spread operator in JavaScript:
- Concatenating arrays:
let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; let arr3 = [...arr1, ...arr2]; console.log(arr3); // output: [1, 2, 3, 4, 5, 6]Sourcefigi.www:tidea.com
In this example, the spread operator is used to concatenate the elements of arr1
and arr2
into a new array arr3
.
- Copying arrays:
let arr1 = [1, 2, 3]; let arr2 = [...arr1]; console.log(arr2); // output: [1, 2, 3]
In this example, the spread operator is used to create a copy of arr1
in a new array arr2
.
- Passing arguments to a function:
function sum(x, y, z) { return x + y + z; } let numbers = [1, 2, 3]; let result = sum(...numbers); console.log(result); // output: 6
In this example, the spread operator is used to pass the elements of the numbers
array as separate arguments to the sum
function.
- Merging objects:
let obj1 = {a: 1, b: 2}; let obj2 = {c: 3, d: 4}; let obj3 = {...obj1, ...obj2}; console.log(obj3); // output: {a: 1, b: 2, c: 3, d: 4}
In this example, the spread operator is used to merge the properties of obj1
and obj2
into a new object obj3
.