Definition and Usage
The spread syntax in JavaScript allows you to individually expand (spread) the items of an object that can be iterated over by value—such as arrays, strings, or DOM collections.
The Spread Syntax is also known as the 'Spread Operator'.
Using the Spread Syntax allows you to easily copy or merge items from arrays or objects.
It enables you to write more concise and simpler code, making it very convenient.
Spread Syntax Format
The Spread Syntax is very simple.
It takes the form of three dots (...) followed by an object that can be iterated over by value—such as an array, string, or DOM collection.
Let's take a look at the basic syntax with examples:
/* Array */
const arr = [1, 2, 3];
console.log(...arr); // Output: 1 2 3
/* String */
const str = "Hello World";
console.log(...str); // Output: "H e l l o W o r l d"
/* DOM Collection */
const items = document.querySelectorAll(".item"); // Returns a NodeList
const itemsArray = [...items]; // Convert to an array using the Spread Syntax
// Now we can use array methods
itemsArray.forEach(item => {
console.log(item.textContent);
});
Basic Example
The following example demonstrates how to easily merge two arrays using the Spread Syntax. As shown in the example, the Spread Syntax allows you to easily copy or merge arrays or objects, enabling you to write shorter and simpler code.
const arr1 = [1, 2];
const arr2 = [3, 4];
const mergedArr = [...arr1, ...arr2]; // Merging arrays
console.log(mergedArr); // [1, 2, 3, 4]
Targets for Using the Spread Syntax
The spread syntax can only be used on objects that can be iterated over by value.
Objects that can be iterated over by value—that is, the targets on which the spread syntax can be used—are as follows:
- Arrays, strings, Map, Set, and other objects with Iteration Protocols applied
HTMLCollectionandNodeListobjects, which are DOM collections- Certain array-like objects such as
arguments - User-defined objects with Iteration Protocols applied
Using the Spread Syntax with Object Literals
Plain objects, such as those created with object literals, can be iterated over by their keys, but not by their values.
This means they are not direct targets for the spread syntax. However, starting from ECMAScript 2018 (ES9), the spread syntax can be used inside object literals to expand the properties of another object literal for merging or copying.
Practical Examples
Through examples, we will explore how to use the spread syntax on objects that can be iterated over by value.
Extending Arrays
The Spread Syntax is very convenient for merging or expanding the elements of an array. You can easily copy elements from an existing array to a new array, add new elements, or merge with another array.
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
// Merging two arrays
const mergedArray = [...arr1, ...arr2];
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
// Expanding the array by adding new elements
const extendedArray = [...arr1, 4, 5];
console.log(extendedArray); // Output: [1, 2, 3, 4, 5]
Passing Arguments to Functions
You can use the Spread Syntax to pass arrays or argument lists when calling functions. This allows you to pass individual arguments from an array, even when the function accepts a variable number of arguments.
function sum(a, b, c) {
return (a + b + c);
}
const numbers = [1, 2, 3];
const result = sum(...numbers); // Equivalent to sum(1, 2, 3)
console.log(result); // Output: 6
Handling DOM with NodeList
Using the Spread Syntax, beginners can more easily work with DOM objects like NodeList. NodeList is a collection of DOM elements that has an array-like object that has an array-like structure, but due to certain behaviors (such as not directly supporting array methods), it can be tricky for beginners.
The Spread Syntax simplifies converting a NodeList into an array or merging it with other arrays.
// Select all elements with the .item class in the HTML document
const items = document.querySelectorAll(".item"); // Returns a NodeList
// Convert the NodeList to an array using the Spread Syntax
const itemsArray = [...items];
// Now that itemsArray is an array, you can use array methods
itemsArray.forEach(item => {
console.log(item.textContent); // Output text content of each .item element
});
// Merging with another array
const newItems = ["New Item 1", "New Item 2"];
const allItems = [...itemsArray, ...newItems]; // Merging the NodeList with the new array
console.log(allItems); // NodeList + new array
Things to Keep in Mind
There are a few important things to keep in mind when using the Spread Syntax.
Do Not Assign the Spread Syntax to a Variable
The Spread Syntax is not an operator that performs an operation on an operand.
Although the Spread Syntax is commonly referred to as the "Spread Operator," this is technically incorrect. An operator must operate on an operand and return a value. Therefore, the Spread Syntax cannot be called a Spread Operator; rather, it is a syntactic feature used in specific contexts.
const items = ...[1, 2, 3, 4]; // Uncaught SyntaxError
Using Spread Syntax with Object Literals
As explained in the section on objects that can be used with the spread syntax, object literals are not objects that can be iterated over by value; they are objects that can be iterated over by key. This means they are not direct targets for the spread syntax.
However, starting with ECMAScript 2018 (ES9), you can use the Spread Syntax inside object literals to spread and merge or copy properties from another object literal.
Object Literals Cannot Directly Use the Spread Syntax
Here's an example where an object literal cannot directly use the Spread Syntax.
const obj = {
a: 1,
b: 2,
c: 3
}
console.log(...obj); // Uncaught TypeError
Spreading and Merging Properties from Another Object Literal
Starting with ECMAScript 2018 (ES9), you can use the Spread Syntax inside object literals to spread and merge or copy properties from other object literals.
const obj1 = {
x: 1,
y: 2
}
const obj2 = {
z: 3
}
// 객체 병합
const mergedObj = {...obj1, ...obj2};
console.log(mergedObj); // { x: 1, y: 2, z: 3 }
Compatibility
| Syntax |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
Node.js
|
|---|---|---|---|---|---|
| Spread syntax (...) | 46 | 12 | 16 | 8 | 5 |
| Spreading and Merging Properties from Another Object Literal | 60 | 79 | 55 | 11.1 | 8.3 |