search
HomeWeb Front-endJS TutorialQuick Tip: How to Use the Spread Operator in JavaScript

Quick Tip: How to Use the Spread Operator in JavaScript

This tutorial will explain the various uses of extended operators in JavaScript, as well as the main differences between extended operators and residual operators.

JavaScript extension operator is represented by three dots (...) and is introduced in ES6. It can expand elements in collections and arrays into single elements.

Extended operators can be used to create and clone arrays and objects, pass arrays as function parameters, delete duplicates in arrays, and more.

Key Points

  • JavaScript extension operator is represented by three dots (...). It was introduced in ES6 to expand elements in sets and arrays into single elements. It can be used to create and clone arrays and objects, pass arrays as function parameters, delete duplicates in arrays, and more.
  • The extension operator can be used to clone arrays and objects, concatenate arrays, convert NodeList to arrays, and delete duplicates in arrays. However, it is important to note that it only performs shallow copies, which means it only copies the top-level elements or attributes. If an array or object contains other array or object, those arrays or objects are copied by reference, not by values.
  • The extension operator is different from the remaining operator, although both use the same syntax as three dots (...). The remaining operators can be used in the function's parameter list, indicating that the function accepts an undefined number of parameters, which can be processed as an array.

Grammar

Extended operators can only be used for iterable objects. It must be immediately before the iterable object, without any separation. For example:

console.log(...arr);

Function parameters

Take Math.min() method as an example. This method takes at least one number as a parameter and returns the smallest number of the passed parameters.

If you have an array of numbers and want to find the minimum value of these numbers, if there is no extension operator, you need to pass elements one by one with the index, or use the apply() method to pass elements of the array as arguments. For example:

const numbers = [15, 13, 100, 20];
const minNumber = Math.min.apply(null, numbers);
console.log(minNumber); // 13

Note that the first parameter is null, because the first parameter is used to change the value of this calling function.

The extension operator is a more convenient and readable solution for passing elements of an array as parameters to a function. For example:

const numbers = [15, 13, 100, 20];
const minNumber = Math.min(...numbers);
console.log(minNumber); // 13

You can see in this online example:

View the example on CodePen

Create an array

The

Extended operator can be used to create new arrays from existing arrays or other iterable objects containing the Symbol.iterator() method. These are objects that can be iterated with a for...of loop.

For example, it can be used to clone arrays. If you just assign the value of the existing array to a new array, making changes to the new array will update the existing array:

console.log(...arr);

By using the extension operator, you can clone an existing array into a new array, and any changes made to the new array will not affect the existing array:

const numbers = [15, 13, 100, 20];
const minNumber = Math.min.apply(null, numbers);
console.log(minNumber); // 13

It should be noted that this will only clone a one-dimensional array. It does not work with multidimensional arrays.

The extension operator can also be used to concatenate multiple arrays into one array. For example:

const numbers = [15, 13, 100, 20];
const minNumber = Math.min(...numbers);
console.log(minNumber); // 13

You can also use the extension operator for strings to create an array where each item is a character in the string:

const numbers = [15, 13, 100, 20];
const clonedNumbers = numbers;
clonedNumbers.push(24);
console.log(clonedNumbers); // [15, 13, 100, 20, 24]
console.log(numbers); // [15, 13, 100, 20, 24]

Create an object

Extension operators can be used to create objects in different ways.

It can be used to lightly clone another object. For example:

const numbers = [15, 13, 100, 20];
const clonedNumbers = [...numbers];
clonedNumbers.push(24);
console.log(clonedNumbers); // [15, 13, 100, 20, 24]
console.log(numbers); // [15, 13, 100, 20]

It can also be used to merge multiple objects into one object. For example:

const evenNumbers = [2, 4, 6, 8];
const oddNumbers = [1, 3, 5, 7];
const allNumbers = [...evenNumbers, ...oddNumbers];
console.log(...allNumbers); //[2, 4, 6, 8, 1, 3, 5, 7]

It should be noted that if the object shares the same property name, the property value of the last extended object will be used. For example:

const str = 'Hello, World!';
const strArr = [...str];
console.log(strArr); // ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']

The extension operator can be used to create objects from an array where the index in the array becomes the attribute and the value at that index becomes the value of the attribute. For example:

const obj = { name: 'Mark', age: 20};
const clonedObj = { ...obj };
console.log(clonedObj); // {name: 'Mark', age: 20}

It can also be used to create objects from strings, similarly, the index in the string becomes the attribute, and the characters at that index become the value of the attribute. For example:

const obj1 = { name: 'Mark', age: 20};
const obj2 = { occupation: 'Student' };
const clonedObj = { ...obj1, ...obj2 };
console.log(clonedObj); // {name: 'Mark', age: 20, occupation: 'Student'}

Convert NodeList to an array

NodeList is a collection of nodes that are elements in the document. Unlike arrays, these elements are accessed through methods in a collection such as items or entries.

You can use the extension operator to convert NodeList to an array. For example:

const obj1 = { name: 'Mark', age: 20};
const obj2 = { age: 30 };
const clonedObj = { ...obj1, ...obj2 };
console.log(clonedObj); // {name: 'Mark', age: 30}

Delete duplicates in the array

Set object is a collection that stores only unique values. Similar to NodeList, Sets can be converted to arrays using the extension operator.

Since Set stores only unique values, it can be paired with the extension operator to delete duplicates in the array. For example:

const numbers = [15, 13, 100, 20];
const obj = { ...numbers };
console.log(obj); // {0: 15, 1: 13, 2: 100, 3: 20}

Extended operator and residual operator

The remaining operator is also a three-point operator (...), but it is used for different purposes. The remaining operators can be used in the function's parameter list, indicating that the function accepts an undefined number of parameters. These parameters can be processed as arrays.

Example:

const str = 'Hello, World!';
const obj = { ...str };
console.log(obj); // {0: 'H', 1: 'e', 2: 'l', 3: 'l', 4: 'o', 5: ',', 6: ' ', 7: 'W', 8: 'o', 9: 'r', 10: 'l', 11: 'd', 12: '!'}

In this example, the remaining operators are used as parameters to calculateSum function. You then iterate over the items in the array and add them to calculate their sum.

You can then pass the variables one by one to the calculateSum function as parameters, or use the extension operator to pass elements of the array as parameters:

const nodeList = document.querySelectorAll('div');
console.log(nodeList.item(0)); // <div>...</div>
const nodeArray = [...nodeList];
console.log(nodeArray[0]); // <div>...</div>

Conclusion

Extended operators allow you to do more with fewer lines of code while keeping the code readable. It can be used for iterable objects, passing parameters to functions, or creating arrays and objects from other iterable objects.

Related readings:

  • Missing mathematical method in JavaScript
  • Quick Tips: How to Sort Object Array in JavaScript
  • How to use for loop in JavaScript
  • Quick tip: Test whether the string matches the regular expression in JavaScript
  • 《JavaScript: From Newbie to Ninja》

JavaScript Extended Operator FAQs (FAQs)

(Frequently asked questions similar to the original FAQ content but with different wordings should be added here to maintain consistency of the content and avoid copying the original text directly)

The above is the detailed content of Quick Tip: How to Use the Spread Operator in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.