Open In App

JavaScript delete Operator

The delete operator in JavaScript removes a property from an object. It can delete both own properties and inherited properties. Using delete on an array item leaves a hole.

Syntax:



delete object
// or
delete object.property
// or
delete object['property']

Parameter: It does not take any parameters.

Return type: This operator returns true if it removes a property. While deleting an object property that doesn’t exist will return a true but it will not affect the object. However, while trying to delete a variable or a function will return a false.



JavaScript delete Operator Examples

Example 1: In this example, the salary property exists in the emp object, the delete operation is successful, and true is logged to the console.




let emp = { 
    firstName: "Raj"
    lastName: "Kumar"
    salary: 40000 
  
console.log(delete emp.salary);
console.log(emp);

Output
true
{ firstName: 'Raj', lastName: 'Kumar' }

Explanation:

The code defines an object `emp` with properties `firstName`, `lastName`, and `salary`. `delete emp.salary` attempts to delete the `salary` property. It returns `true` if successful, and `false` otherwise. However, the property is still present in the `emp` object, as demonstrated by the subsequent `console.log(emp)`.

Example 2: Here’s an example illustrating the behavior of delete with a non-configurable property




// Define an object with a non-configurable property
let obj = {
    name: "John"
};
  
Object.defineProperty(obj, 'age', {
    value: 30,
    configurable: false // Making 'age' property non-configurable
});
  
console.log(obj); // { name: 'John', age: 30 }
  
// Attempt to delete the non-configurable property 'age'
let result = delete obj.age;
console.log(result); // false, deletion fails
  
console.log(obj); // { name: 'John', age: 30 }

Output
{ name: 'John' }
false
{ name: 'John' }

Explanation:

Example 3: Here, we are deleting Array Values Using delete




let arr = [1, 2, 3]
  
console.log(delete arr[0]); //true
console.log(arr); //[empty, 2, 3]

Output
true
[ <1 empty item>, 2, 3 ]

Explanation:

Example 4: In JavaScript, global properties declared with var or created without any declaration can be deleted.




var globalVar = 10;
let localVar = 20;
  
console.log(delete globalVar); // true, deletion successful
console.log(delete localVar);  // false, deletion fails
  
console.log(globalVar); // undefined
console.log(localVar);  // 20, deletion failed

Output
false
false
10
20

Explanation:

Conclusion:

There are other ways used by developers, such as setting the value of an object property to null or undefined. But the property will still exist on the object and some operators like for in loop will still show the presence of the null or undefined property. Using the delete property in loops slows down the program significantly. So, this method should only be used when it is absolutely necessary to delete an object property.


Article Tags :