Definition and Usage
The Spread Syntax in JavaScript is an easy way to individually spread and list the items of iterable objects (such as arrays, strings, and 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 consists of using three dots (...
) followed by the iterable object (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 with iterable objects.
JavaScript has established a unified set of rules for objects that are iterable. This set of rules is known as the Iterable Protocol, and iterable objects are those that adhere to this protocol.
The types of objects that can use the Spread Syntax are as follows:
- Arrays: Each element of an array
- Strings: Each character of a string
- DOM Collection Objects (
NodeList
,HTMLCollection
): Each element object Map
Objects: Each key-value pairSet
Objects: Each value- Function
arguments
Object: Each argument
Using the Spread Syntax with Object Literals
Object literals are not iterable objects.
This means you cannot directly apply the Spread Syntax to them.
However, starting with ECMAScript 2018 (ES9), you can use the Spread Syntax inside object literals to spread the properties of another object literal, allowing for merging or copying.
Practical Examples
Let's explore how to use the Spread Syntax with iterable objects through practical examples.
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 targets for the Spread Syntax, object literals are not iterable objects. This means you cannot directly use the Spread Syntax with them.
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 }
Browser compatibility
Syntax |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
---|---|---|---|---|
Spread syntax (...) | 46 | 12 | 16 | 8 |
Spreading and Merging Properties from Another Object Literal | 60 | 79 | 55 | 11.1 |