Table of Contents
1. Exchange variables" >1. Exchange variables
2. Accessing elements in the array" >2. Accessing elements in the array
3. Immutable operations" >3. Immutable operations
5. Destructuring dynamic properties" >5. Destructuring dynamic properties
6. Conclusion" >6. Conclusion
Home Web Front-end JS Tutorial 5 ways to use destructuring in JavaScript

5 ways to use destructuring in JavaScript

Nov 30, 2020 pm 06:00 PM
javascript

5 ways to use destructuring in JavaScript

Reading object properties and accessing array items are common operations. Destroying allocations makes these operations easier and cleaner. In this article, in addition to the basic usage, I will also introduce 5 interesting uses of destructuring in JavaScript.

1. Exchange variables

Usually the method of exchanging two variables requires an additional temporary variable. Let’s take a look at the example:

let a = 1;
let b = 2;
let temp;

temp = a;
a = b;
b = temp;

a; // => 2
b; // => 1
Copy after login

temp is a temporary variable, which first saves the value of a. Then assign the value of b to a, and then assign the value of temp to b.

It will be simpler if you use destructuring, there is no need for any crazy temp variables.

let a = 1;
let b = 2;

[a, b] = [b, a];

a; // => 2
b; // => 1
Copy after login

[a, b] = [b, a] is a destructuring assignment. On the right, an array [b, a] is created, that is, [2,1]. This array 2 is assigned to a, and 1 is assigned to b.

Although this method also creates a temporary array, this method looks at least more concise. Using destructuring, we can also exchange more than 2 variables.

let zero = 2;
let one = 1;
let two = 0;

[zero, one, two] = [two, one, zero];

zero; // => 0
one;  // => 1
two;  // => 2
Copy after login

2. Accessing elements in the array

There is a scenario where we may have an empty item array. and want to access the first, second, or nth item of an array, but if the item does not exist, use the specified default value.

Usually the length attribute of the array is used to determine

const colors = [];

let firstColor = 'white';
if (colors.length > 0) {
 firstColor = colors[0];
}

firstColor; // => 'white'
Copy after login

Using array destructuring, the same effect can be achieved more concisely:

const colors = [];

const [firstColor = 'white'] = colors;

firstColor; // => 'white'
Copy after login

const [firstColor = 'white'] = colors Destructuring assigns the first element of the colors array to the firstColor variable. If the array does not have any elements at index 0, the "white" default value is assigned.

Of course it can be more flexible. If you only want to access the second element, you can do this.

const colors = [];

const [, secondColor = 'black'] = colors;

secondColor; // => 'black'
Copy after login

Note the comma on the left side of the deconstruction: it means to ignore the first element, secondColoruse the element with index 1 in the colors array Make an assignment.

3. Immutable operations

When I started using React and Redux, I was forced to write some compliance Immutable code. Although it was a bit difficult at first, I later saw its benefits: it was easier to handle one-way data flow.

Immutability requires that the original object cannot be changed. Fortunately, destructuring makes it easy to implement certain operations in an immutable way.

const numbers = [1, 2, 3];

const [, ...fooNumbers] = numbers;

fooNumbers; // => [2, 3]
numbers; // => [1, 2, 3]
Copy after login

Destructuring[, ... fooNumbers] = numbersCreates a new array fooNumbers, fooNumbers containing numbers elements, except the first element.

numbers The array has not changed and the operation remains unchanged.

In the same immutable way, you can delete attributes from the object, and then try to delete the foo attribute from the object big:

const big = {
 foo: 'value Foo',
 bar: 'value Bar'
};

const { foo, ...small } = big;

small; // => { bar: 'value Bar' }
big; // => { foo: 'value Foo', bar: 'value Bar' }
Copy after login

4. Destructuring iterables

In the previous examples, destructuring was used for arrays, but we can destructure any object that implements the iterable protocol.

Many native primitive types and objects are iterable: array, string, typed arrays, set and map.

If you don’t want to be limited to basic types, you can customize the destructuring logic by implementing the iterable protocol.

movies Contains a list of movie objects. It's great to get title as a string when deconstructing movies. Let's implement a custom iterator.

const movies = {
  list: [
    { title: 'Heat' }, 
    { title: 'Interstellar' }
  ],
  [Symbol.iterator]() {
    let index = 0;
    return {
      next: () => {
        if (index < this.list.length) {
          const value = this.list[index++].title;
          return { value, done: false };
        }
        return { done: true };
      }
    };
  }
};

const [firstMovieTitle] = movies;
console.log(firstMovieTitle); // => 'Heat'
Copy after login

movies The object implements the iterable protocol by defining the Symbol.iterator method, and the iterator iterates title.

Follows the iterable protocolallows movies objects to be decomposed into title by reading the first movies The title:const [firstMovieTitle] = movies.

5. Destructuring dynamic properties

As a rule of thumb, object destructuring through properties is more common than array destructuring.

The destructuring of the object looks very simple:

const movie = { title: 'Heat' };

const { title } = movie;

title; // => 'Heat'
Copy after login

const {title} = movieCreate a variable title and set the attribute ## The value of #movie.title is assigned to it.

When it comes to object destructuring, I was a little surprised that we don’t have to know the property names statically and can use dynamic property names to deconstruct the object.

To understand how dynamic destructuring works, write a

greet function:

function greet(obj, nameProp) {
 const { [nameProp]: name = 'Unknown' } = obj;
 return `Hello, ${name}!`;
}

greet({ name: 'Batman' }, 'name'); // => 'Hello, Batman!'
greet({ }, 'name'); // => 'Hello, Unknown!'
Copy after login
Call

greet()# with 2 arguments ## Functions: object and property names. Inside

greet()

, destructuring assignment const {[nameProp]:name ='Unknown'} = objUse the form of square brackets[nameProp ]Read the dynamic attribute name, and the name variable receives the dynamic attribute value. A better approach is to specify a default value of "

Unknown

" if the property does not exist. <h2 id="span-style-font-size-px-Conclusion-span"><span style="font-size: 18px;">6. Conclusion</span></h2> <p> Destruction is very useful if you want to access object properties and array items. </p> <p>In addition to basic usage, array destructor can also conveniently exchange variables, access array items, and perform some immutable operations. </p> <p>JavaScript offers greater possibilities, as you can define custom destruction logic using iterators. </p> <blockquote><p>Original address: https://dmitripavlutin.com/5-interesting-uses-javascript-destructuring/</p></blockquote> <p>For more programming-related knowledge, please visit: <a href="https://www.php.cn/course.html" target="_blank" textvalue="编程学习">programminglearning</a>! ! </p>

The above is the detailed content of 5 ways to use destructuring in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles