Skip to main content

Objects, Arrays & Destructuring

Objects​

Dùng literal syntax để tạo object​

// ❌ Tránh
const item = new Object();

// ✅ Tốt
const item = {};

Dùng computed property names khi tên property động​

function getKey(k) {
return `a key named ${k}`;
}
// ❌ Tránh
const obj = { id: 5, name: "San Francisco" };
obj[getKey("enabled")] = true;
// ✅ Tốt
const obj = {
id: 5,
name: "San Francisco",
[getKey("enabled")]: true,
};

Dùng method shorthand​

// ❌ Tránh
const atom = {
value: 1,
addValue: function (value) {
return atom.value + value;
},
};
// ✅ Tốt
const atom = {
value: 1,
addValue(value) {
return atom.value + value;
},
};

Dùng property value shorthand​

const lukeSkywalker = "Luke Skywalker";
// ❌ Tránh
const obj = { lukeSkywalker: lukeSkywalker };
// ✅ Tốt
const obj = { lukeSkywalker };

Ưu tiên spread ... thay vì Object.assign để copy nông​

// ❌ Tránh
const copy = Object.assign({}, original, { c: 3 });
// ✅ Tốt
const copy = { ...original, c: 3 };
const { a, ...noA } = copy;

Không gọi trực tiếp Object.prototype (vd. hasOwnProperty)​

Dùng Object.prototype.hasOwnProperty.call(object, key) hoặc Object.hasOwn(object, key) (ES2022).


Arrays​

Dùng literal syntax để tạo array​

// ❌ Tránh
const items = new Array();
// ✅ Tốt
const items = [];

Dùng Array#push thay vì gán trực tiếp khi thêm phần tử​

const someStack = [];
// ✅ Tốt
someStack.push("abracadabra");

Dùng spread ... để copy array​

// ✅ Tốt
const itemsCopy = [...items];

Dùng Array.from để chuyển array-like / iterable thành array​

const arrLike = { 0: "foo", 1: "bar", 2: "baz", length: 3 };
// ✅ Tốt
const arr = Array.from(arrLike);

Có return trong callback của array methods khi cần​

// ✅ Tốt
[1, 2, 3].map((x) => {
const y = x + 1;
return x * y;
});
// ✅ Tốt
[1, 2, 3].map((x) => x + 1);

Destructuring​

Dùng object destructuring khi dùng nhiều property của object​

// ❌ Tránh
function getFullName(user) {
const firstName = user.firstName;
const lastName = user.lastName;
return `${firstName} ${lastName}`;
}
// ✅ Tốt
function getFullName({ firstName, lastName }) {
return `${firstName} ${lastName}`;
}

Dùng array destructuring​

const arr = [1, 2, 3, 4];
// ✅ Tốt
const [first, second] = arr;

Nhiều giá trị trả về: dùng object destructuring, không dùng array​

Để sau này thêm property hoặc đổi thứ tự không làm vỡ chỗ gọi.

// ✅ Tốt
function processInput(input) {
return { left, right, top, bottom };
}
const { left, top } = processInput(input);