Technology Sharing

What is destructuring assignment in JavaScript?

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

A little bit of progress every day


⭐ Column Introduction

Front-end Beginner's Journey: Exploring the Wonderful World of Web Development Welcome to the front-end entry journey! If you are interested, you can subscribe to this column! This column is for those who are interested inWeb DevelopmentThis column is tailor-made for those who are interested and have just entered the front-end field. Whether you are a complete novice or a developer with some basics, this column will provide you with a systematic and friendly learning platform. In this column, we will update it every day in the form of questions and answers to present selected front-end knowledge points and frequently asked questions. Through the question-and-answer format, we hope to respond more directly to readers' questions about front-end technology and help everyone gradually build a solid foundation. Whether it is HTML, CSS, JavaScript or various commonly used frameworks and tools, we will explain the concepts in a simple way and provide practical cases and exercises to consolidate what you have learned. At the same time, we will also share some practical tips and best practices to help you better understand and apply various technologies in front-end development.

insert image description here

Whether you are looking for a career change, to improve your skills, or to satisfy your personal interests, we will do our best to provide you with the best learning resources and support. Let's explore the wonderful world of web development together! Join the front-end entry journey and become an excellent front-end developer! Let's embark on the front-end journey!!!

Today's content:What is destructuring assignment in JavaScript?

insert image description here


What is destructuring assignment in JavaScript?

1 Introduction

Destructuring assignment is a syntax introduced by ES6 that allows you to extract values ​​from arrays or objects and assign them to different variables. Destructuring assignment makes data extraction more concise and clear, and simplifies the code structure. This article will explain in detail the concept, syntax, and application of destructuring assignment in actual programming.

2. The concept of destructuring assignment

Destructuring assignment is a way to extract data from an array or object and assign it to a separate variable. It can simplify data extraction operations and avoid accessing object properties or array elements multiple times.

3. Array destructuring assignment

3.1 Basic Syntax

Array destructuring assignment allows us to extract values ​​from an array and assign them to a variable.

const [a, b, c] = [1, 2, 3];
console.log(a); // 输出: 1
console.log(b); // 输出: 2
console.log(c); // 输出: 3
  • 1
  • 2
  • 3
  • 4

3.2 Skipping Elements

You can skip certain elements in an array and extract only the values ​​you want.

const [a, , c] = [1, 2, 3];
console.log(a); // 输出: 1
console.log(c); // 输出: 3
  • 1
  • 2
  • 3

3.3 Default Values

You can specify a default value for a destructuring variable when the corresponding array element isundefined, the default value will take effect.

const [a, b = 2] = [1];
console.log(a); // 输出: 1
console.log(b); // 输出: 2
  • 1
  • 2
  • 3

3.4 Swapping variable values

Destructuring assignment provides a concise way to swap the values ​​of two variables.

let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a); // 输出: 2
console.log(b); // 输出: 1
  • 1
  • 2
  • 3
  • 4
  • 5

4. Object destructuring assignment

4.1 Basic Syntax

Object destructuring allows us to extract property values ​​from an object and assign them to a variable.

const person = { name: 'John', age: 30 };
const { name, age } = person;
console.log(name); // 输出: John
console.log(age); // 输出: 30
  • 1
  • 2
  • 3
  • 4

4.2 Renaming variables

You can rename variables during destructuring assignment to avoid variable name conflicts or improve code readability.

const person = { name: 'John', age: 30 };
const { name: userName, age: userAge } = person;
console.log(userName); // 输出: John
console.log(userAge); // 输出: 30
  • 1
  • 2
  • 3
  • 4

4.3 Default Values

You can specify default values ​​for variables assigned by object destructuring when the corresponding property does not exist or the value isundefined, the default value will take effect.

const person = { name: 'John' };
const { name, age = 25 } = person;
console.log(name); // 输出: John
console.log(age); // 输出: 25
  • 1
  • 2
  • 3
  • 4

4.4 Nested Destructuring

You can extract values ​​from nested properties of an object through nested destructuring.

const person = { name: 'John', address: { city: 'New York', zip: 10001 } };
const { address: { city, zip } } = person;
console.log(city); // 输出: New York
console.log(zip); // 输出: 10001
  • 1
  • 2
  • 3
  • 4

5. Application of destructuring assignment

5.1 Function Parameters

Destructuring assignment can be used for function parameters to simplify function parameter processing.

function displayPerson({ name, age }) {
  console.log(`Name: ${name}, Age: ${age}`);
}

const person = { name: 'John', age: 30 };
displayPerson(person); // 输出: Name: John, Age: 30
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

5.2 Extracting function return values

Destructuring assignment can be used to extract values ​​from arrays or objects returned by functions.

function getCoordinates() {
  return [40.7128, -74.0060];
}

const [latitude, longitude] = getCoordinates();
console.log(`Latitude: ${latitude}, Longitude: ${longitude}`); // 输出: Latitude: 40.7128, Longitude: -74.0060
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

5.3 Handling multiple return values

Destructuring assignment can be used to handle multiple values ​​returned by a function, avoiding the use of array indices or object property names.

function getUserInfo() {
  return { name: 'John', age: 30, city: 'New York' };
}

const { name, age, city } = getUserInfo();
console.log(name); // 输出: John
console.log(age); // 输出: 30
console.log(city); // 输出: New York
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

6. Conclusion

Destructuring assignment is a concise syntax in JavaScript to extract values ​​from an array or object and assign them to a variable. Destructuring assignment makes it easier to extract data, process function parameters, extract function return values, and simplify code structure. Mastering destructuring assignment technology can improve code readability and maintainability, and improve development efficiency.


⭐ Last words

This column is suitable for a wide range of readers, including front-end beginners; or partners who have not learned the front-end but are interested in it, or back-end students who want to better demonstrate themselves and expand some small front-end knowledge points during the interview. So if you have the foundation of the front-end and follow this column to learn, it can also help you to fill in the gaps to a great extent. Since the blogger himself is doing the content output, if there are any flaws in the article, you can contact me on the left side of the homepage, and we will make progress together. At the same time, I also recommend several columns to everyone. Interested partners can subscribe: In addition to the columns below, you can also go to my homepage to see other columns;

Front-end games (free)This column will take you into a world full of creativity and fun. By using the basics of HTML, CSS, and JavaScript, we will build various interesting web games together. Whether you are a beginner or have some front-end development experience, this column is suitable for you. We will start with the most basic knowledge and guide you step by step to master the skills needed to build web games. Through practical cases and exercises, you will learn how to use HTML to build page structures, use CSS to beautify the game interface, and use JavaScript to add interactive and dynamic effects to the game. In this column, we will cover various types of games, including maze games, brick breaking, snakes, minesweepers, calculators, airplane battles, tic-tac-toe games, puzzles, mazes, and more. Each project will guide you through the construction process in concise and clear steps, and provide detailed explanations and code examples. At the same time, we will also share some optimization tips and best practices to help you improve page performance and user experience. Whether you are looking for an interesting project to exercise your front-end skills or are interested in web game development, the front-end game column will be your best choice.Click to subscribe to the front-end game column

insert image description here

Vue3 Transparent Tutorial [From Zero to One] (Paid) Welcome to the Vue3 Transparent Tutorial! This column aims to provide you with comprehensive Vue3-related technical knowledge. If you have some Vue2 experience, this column can help you master the core concepts and usage of Vue3. We will start from scratch and guide you step by step to build a complete Vue application. Through practical cases and exercises, you will learn how to use Vue3's template syntax, component development, state management, routing and other functions. We will also introduce some advanced features, such as Composition API and Teleport, to help you better understand and apply Vue3's new features. In this column, we will guide you through each project in concise and clear steps, and provide detailed explanations and sample code. At the same time, we will also share some common problems and solutions in Vue3 development to help you overcome difficulties and improve development efficiency. Whether you want to learn Vue3 in depth or need a comprehensive guide to build a front-end project, the Vue3 Transparent Tutorial column will become an indispensable resource for you.Click to subscribe to the Vue3 Transparent Tutorial [From Zero to One] column

insert image description here

TypeScript Getting Started Guide (Free) This is a column designed to help everyone quickly get started and master TypeScript-related technologies. Through concise and clear language and rich sample code, we will explain in depth the basic concepts, syntax, and features of TypeScript. Whether you are a beginner or an experienced developer, you can find a learning path that suits you here. From core features such as type annotations, interfaces, and classes to modular development, tool configuration, and integration with common front-end frameworks, we will cover all aspects. By reading this column, you will be able to improve the reliability and maintainability of JavaScript code, and provide better code quality and development efficiency for your own projects. Let's embark on this exciting and challenging TypeScript journey together!Click to subscribe to the TypeScript Getting Started Guide column

insert image description here