What is the spread operator and how is it used?
TL;DR
The spread operator, represented by three dots (...
), is used in JavaScript to expand iterable objects like arrays or strings into individual elements. It can also be used to spread object properties. For example, you can use it to combine arrays, copy arrays, or pass array elements as arguments to a function.
const arr1 = [1, 2, 3];const arr2 = [4, 5, 6];const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]const obj1 = { a: 1, b: 2 };const obj2 = { c: 3, d: 4 };const combinedObj = { ...obj1, ...obj2 }; // { a: 1, b: 2, c: 3, d: 4 }
What is the spread operator and how is it used?
Expanding arrays
The spread operator can be used to expand elements of an array into individual elements. This is useful for combining arrays or copying arrays.
const arr1 = [1, 2, 3];const arr2 = [4, 5, 6];const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
Copying arrays
You can create a shallow copy of an array using the spread operator.
const original = [1, 2, 3];const copy = [...original]; // [1, 2, 3]
Passing array elements as function arguments
The spread operator can be used to pass elements of an array as arguments to a function.
function sum(a, b, c) {return a + b + c;}const numbers = [1, 2, 3];const result = sum(...numbers); // 6
Expanding objects
The spread operator can also be used to expand properties of an object. This is useful for combining objects or copying objects.
const obj1 = { a: 1, b: 2 };const obj2 = { c: 3, d: 4 };const combinedObj = { ...obj1, ...obj2 }; // { a: 1, b: 2, c: 3, d: 4 }
Copying objects
You can create a shallow copy of an object using the spread operator.
const originalObj = { a: 1, b: 2 };const copyObj = { ...originalObj }; // { a: 1, b: 2 }
Using with strings
The spread operator can also be used to expand a string into individual characters.
const str = 'hello';const chars = [...str]; // ['h', 'e', 'l', 'l', 'o']