What is Spread Operator in JavaScript: Simple Explanation and Examples
The
spread operator in JavaScript is written as ... and lets you expand elements of an array or properties of an object into individual elements. It helps combine, copy, or pass elements easily without changing the original data.How It Works
Think of the spread operator as a way to unpack a box full of items and lay them out one by one. Instead of carrying the whole box, you spread out the contents so you can use each item separately.
In JavaScript, when you use ... before an array or object, it takes all the elements or properties inside and spreads them out. This makes it easy to combine arrays, copy them, or pass multiple values to a function without manually listing each item.
Example
This example shows how the spread operator copies an array and combines two arrays into one.
javascript
const fruits = ['apple', 'banana']; const moreFruits = ['orange', 'grape']; // Copying an array const copyFruits = [...fruits]; // Combining arrays const allFruits = [...fruits, ...moreFruits]; console.log(copyFruits); console.log(allFruits);
Output
[ 'apple', 'banana' ]
[ 'apple', 'banana', 'orange', 'grape' ]
When to Use
Use the spread operator when you want to:
- Make a copy of an array or object without changing the original.
- Combine multiple arrays or objects into one.
- Pass elements of an array as separate arguments to a function.
For example, if you have a list of ingredients and want to add more without changing the original list, spreading helps you create a new list easily.
Key Points
- The spread operator is
...and works with arrays and objects. - It helps avoid manual copying or combining of elements.
- It does not change the original array or object but creates a new one.
- It can be used in function calls to pass multiple arguments.
Key Takeaways
The spread operator
... expands elements of arrays or objects into individual parts.It is useful for copying, combining, and passing elements without modifying the original data.
Using spread makes code cleaner and easier to read when handling multiple values.
It works with arrays, objects, and function arguments for flexible programming.