The delete operator
The delete operator in JavaScript is used to remove properties from objects (or elements from arrays).
But it has several subtle nuances worth knowing.
Let's go through it in detail.
Syntax
delete object.propertyor
delete object['property']Example with an object
const user = {
name: 'Tim',
age: 25
};
delete user.age;
console.log(user); // { name: 'Tim' }
console.log('age' in user); // falseThe
deleteoperator removes the property itself from the object, not just its value.
Return value
delete returns a logical value:
| Case | Returns |
|---|---|
| Deletion succeeded | true |
| Deletion is impossible (e.g., the property is "non-configurable") | false |
Example:
const obj = {};
Object.defineProperty(obj, 'x', { value: 10, configurable: false });
console.log(delete obj.x); // false
console.log(obj.x); // 10Example with an array
const arr = [10, 20, 30];
delete arr[1];
console.log(arr); // [10, <1 empty item>, 30]
console.log(arr.length); // 3Important:
deletedoes not shift array elements, it simply removes the value, leaving a "hole" (empty).
If you need to remove an element while changing the array's length, use methods like:
arr.splice(1, 1); // removes the element and shifts the restExample with an object and undefined
The difference between delete and assigning undefined:
const user = { name: 'Tim', age: 25 };
user.age = undefined;
console.log(user); // { name: 'Tim', age: undefined }
console.log('age' in user); // true (the key remains)
delete user.age;
console.log(user); // { name: 'Tim' }
console.log('age' in user); // false (the key is removed)
deleteremoves the key entirelyundefined- just clears the value
Example with a prototype
delete does not affect properties inherited through the prototype:
const person = { name: 'Alex' };
const user = Object.create(person);
console.log('name' in user); // true
delete user.name; // won't delete from the prototype
console.log('name' in user); // trueIt only removes the object's own properties.
Limitations
deletedoes not work on variables declared withvar,let,const:
let x = 10;
console.log(delete x); // false
console.log(x); // 10You can only delete a property of an object, not a variable.
- In strict mode (
"use strict"), an attempt to delete a non-deletable property will cause an error:
"use strict";
delete Object.prototype; // TypeErrorSummary
| What it does | Removes a property from an object |
|---|---|
| Works with | Objects, arrays |
| Returns | true or false |
| Does not work for | Variables (var, let, const) |
| Does not shift array elements | Leaves a "hole" |
| Safe for | An object's own properties |
In short
const obj = { a: 1, b: 2 };
delete obj.a;
console.log(obj); // { b: 2 }
console.log('a' in obj); // falseShort Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.