Destructuring in JavaScript
1. What Is Destructuring?
Destructuring is a JavaScript feature that allows us to extract values from arrays and properties from objects and store them in separate variables.
It helps us write cleaner and shorter code.
2. Array Destructuring
Let's take a simple example.
const fruits = ["Apple", "Banana", "Mango"]; const [first, second, third] = fruits; console.log(first); console.log(second); console.log(third); Output:
Apple Banana Mango Here, the values are assigned based on their positions in the array.
-
firstgets Apple. -
secondgets Banana. -
thirdgets Mango.
3. Skipping Array Elements
We can skip elements using commas.
const numbers = [10, 20, 30, 40]; const [first, , third] = numbers; console.log(first); console.log(third); Output:
10 30 Here, we skipped the second element.
4. Default Values in Array Destructuring
We can assign default values if an array element is undefined.
const numbers = [10]; const [a, b = 20] = numbers; console.log(a); console.log(b); Output:
10 20 Since the second element doesn't exist, the default value 20 is assigned.
5. Object Destructuring
We can also extract properties from objects.
const student = { name: "Lokesh", age: 22, course: "Java" }; const { name, age, course } = student; console.log(name); console.log(age); console.log(course); Output:
Lokesh 22 Java Unlike arrays, object destructuring uses property names instead of positions.
6. Renaming Variables
We can give different names to variables while destructuring objects.
const student = { name: "Lokesh", age: 22 }; const { name: studentName, age: studentAge } = student; console.log(studentName); console.log(studentAge); Output:
Lokesh 22 Here, name is stored in studentName, and age is stored in studentAge.
7. Default Values in Object Destructuring
We can provide default values when an object property is missing or has the value undefined.
const student = { name: "Lokesh" }; const { name, age = 21 } = student; console.log(name); console.log(age); Output:
Lokesh 21 Since the age property is not available, the default value 21 is used.
Remember:
- Array destructuring uses
[]. - Object destructuring uses
{}. - Arrays use positions to extract values.
- Objects use property names to extract values.
- We can skip elements, rename variables, and assign default values.
原文:https://www.a8q9.cn/en/article/destructuring-in-javascript-65006e.html