Javascript: Destructuring assignment

48 sec read

Write Cleaner Code by Using JavaScript Destructuring

Cú pháp destructuring assignment trong javascript cho phép tách giá từ array hoặc property của object thành các variable độc lập

Array destructuring

const colors = ["red", "green", "blue"];
const [firstColor, secondColor, thirdColor] = colors;

console.log(firstColor);  // "red"
console.log(secondColor); // "green"
console.log(thirdColor);  // "blue"

Object destructuring

const person = {
  firstName: "John",
  lastName: "Doe",
  age: 30
};

const { firstName, lastName } = person;

console.log(firstName); // "John"
console.log(lastName);  // "Doe"

Function parameter destructuring

function printFullName({ firstName, lastName }) {
  console.log(`${firstName} ${lastName}`);
}

const person = {
  firstName: "Alice",
  lastName: "Smith"
};

printFullName(person); // "Alice Smith"

Default value

const [a = 1] = []; // a is 1
const { b = 2 } = { b: undefined }; // b is 2
const { c = 2 } = { c: null }; // c is null

const { b = console.log("hey") } = { b: 2 };
// Does not log anything, because `b` is defined and there's no need
// to evaluate the default value.

Rest property

const { a, ...others } = { a: 1, b: 2, c: 3 };
console.log(others); // { b: 2, c: 3 }

const [first, ...others2] = [1, 2, 3];
console.log(others2); // [2, 3]

Lưu ý: rest property phải nằm cuối cùng của pattern

const [a, ...b,] = [1, 2, 3];

// SyntaxError: rest element may not have a trailing comma
// Always consider using rest operator as the last element

Swapping variables

let a = 1;
let b = 3;

[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1

const arr = [1, 2, 3];
[arr[2], arr[1]] = [arr[1], arr[2]];
console.log(arr); // [1, 3, 2]

Tham khảo: Destructuring assignment – JavaScript | MDN (mozilla.org)

Avatar photo

Leave a Reply

Your email address will not be published. Required fields are marked *