delete là toán tử (operator) và từ khóa dành riêng trong JavaScript – KHÔNG THỂ ghi đè, override hoặc tái triển khai. Bài gốc có nhầm lẫn khi nói "reimplement delete method".
Thực tế về delete
- Là operator, không phải function/method.
- Dùng để xóa property khỏi object.
- Không thể xóa biến (var/let/const), function parameter, function name.
- Không thể xóa property non-configurable (strict mode ném TypeError).
- Trả về
truenếu xóa thành công hoặc property không tồn tại,falsenếu thất bại (non-configurable, non-strict).
Cú pháp và ví dụ
const obj = { name: "John", age: 30, city: "Hanoi" };
// Xóa property
delete obj.age; // true
console.log(obj); // { name: "John", city: "Hanoi" }
// Xóa property không tồn tại
delete obj.salary; // true (không báo lỗi, trả true)
// Xóa element mảng (tạo sparse array - KHÔNG khuyến khích)
const arr = [1, 2, 3];
delete arr[1]; // true
console.log(arr); // [1, empty, 3] - length vẫn là 3!
console.log(1 in arr); // false
// Nên dùng: arr.splice(1, 1) → [1, 3]
Ví dụ từ bài gốc (đã sửa)
const cricketer = {
name: "John",
rank: 3,
points: 800
};
delete cricketer.rank; // Xóa property rank
console.log(cricketer); // { name: "John", points: 800 }
// cricketer.rank → undefined
Khi nào delete thất bại (trả false / TypeError)
// 1. Non-configurable property
const obj = {};
Object.defineProperty(obj, "fixed", {
value: 1,
configurable: false
});
delete obj.fixed; // false (sloppy) / TypeError (strict)
// 2. Strict mode + non-configurable
"use strict";
delete Object.prototype; // TypeError
// 3. Biến / Function declaration
var x = 1;
delete x; // false / SyntaxError (strict)
function foo() {}
delete foo; // false / SyntaxError (strict)
// 4. Non-writable nhưng configurable? -> delete vẫn được (configurable mới quan trọng)
Điều GÌ KHÔNG THỂ LÀM với delete
- ❌ Override toán tử
delete(không phải function). - ❌ Tạo hàm tên
delete(reserved word). - ❌ Xóa biến cục bộ (
var,let,const). - ❌ Xóa property non-configurable.
- ❌ Xóa element mảng và mong length giảm (dùng
splice,filter,pop,shift).
Điều CÓ THỂ LÀM (Alternatives)
- ✅ Gán
undefined:obj.prop = undefined(property còn đó, giá trị undefined). - ✅ Gán
null:obj.prop = null. - ✅ Destructuring loại bỏ:
const { prop, ...rest } = obj;(tạo object mới). - ✅
Reflect.deleteProperty(obj, 'prop')– functional form, trả boolean.
Tóm tắt
deletelà operator, KHÔNG thể reimplement/override.- Dùng để xóa own property configurable của object.
- Không xóa được biến, function declaration, non-configurable property.
- Xóa mảng → sparse array (không khuyến khích, dùng splice/filter).
- Strict mode bắt lỗi sớm hơn.