1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
| // Array Destructuring
const numbers = [1, 2, 3, 4, 5];
const [first, second] = numbers; // first = 1, second = 2
const [a, , c] = numbers; // a = 1, c = 3 (skip 2)
const [x, y, ...rest] = numbers; // x = 1, y = 2, rest = [3, 4, 5]
// Default values
const [p = 0, q = 0] = [10]; // p = 10, q = 0
// Swap variables
let m = 1, n = 2;
[m, n] = [n, m]; // m = 2, n = 1
// Object Destructuring
const person = {
name: "Xuân Dương",
age: 21,
university: "HUTECH",
skills: ["Java", "JavaScript"]
};
const { name, age } = person;
console.log(name); // "Xuân Dương"
// Rename variables
const { name: fullName, age: years } = person;
console.log(fullName); // "Xuân Dương"
// Default values
const { country = "Vietnam" } = person;
console.log(country); // "Vietnam"
// Nested destructuring
const student = {
name: "Dương",
scores: { math: 9, english: 8 }
};
const { scores: { math, english } } = student;
// Function parameters
function introduce({ name, age, university }) {
console.log(`${name}, ${age} tuổi, ${university}`);
}
introduce(person);
|