How does the spread operator work in JavaScript?
Asked on Jul 16, 2024
Answer
The spread operator in JavaScript, represented by "...", allows you to expand iterable elements like arrays or objects into individual elements. It is commonly used for copying, merging, and passing elements as arguments.
<!-- BEGIN COPY / PASTE -->
const numbers = [1, 2, 3];
const moreNumbers = [4, 5, ...numbers];
console.log(moreNumbers); // Output: [4, 5, 1, 2, 3]
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, ...obj1 };
console.log(obj2); // Output: { c: 3, a: 1, b: 2 }
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with JavaScript best practices.- The spread operator can be used to merge arrays or objects by expanding their elements.
- In the array example, "numbers" is expanded into "moreNumbers", resulting in a new array.
- In the object example, "obj1" is expanded into "obj2", creating a new object with combined properties.
- It is useful for immutably copying data structures.
Recommended Links:
← Back to All Questions