Understanding delete operator in Javascript

Delete operator is used to delete the property of an object. It completely remove the property and keep the rest of the object intact.

  • The delete operator will not delete ordinary variables.
  • It cannot delete properties of the global object, which were declared with the var keyword.
  • However, it will delete “global variables,” which were not declared with var keyword. since they are actually properties of the global object ( window in the browser).
  • The delete operator doesn’t delete prototype property.

For examples:

var person = { rank : 1};
var result = (function(){
    delete person.rank;
    return person.rank;
  })();
  console.log(result); // undefined

The result would be undefined. In the above code, we have an object named as “person” which has the property “rank”, and as it is a self-invoking function, we will delete the “rank” property from object “person”. When we console.log the reference of the property the result will be undefined.

Let us go through some examples where delete operator doesn’t work:

var result = (function(number){
    delete number;
    return number;
  })(5);  
  console.log(result); // 5

The result would be 5. Delete operators don’t affect local variables. Here, “number” is not an object but a local variable. The delete operator will not delete ordinary variables.

 var number = 5;
var result = (function(){
    delete number;
    return number;
  })();
  console.log(result); // 5

The result would be 5. Delete operators don’t affect global variables declared with var keyword. Here, “number” is not an object but a global variable of type number.

 number = 5; // var is not used. hence it is a property of window.
delete window.number;
console.log(number); // ReferenceError: number is not defined

The result would be “number is not defined”. Here, the global variable “number” is not defined with var keyword. hence, the delete operator will delete “number” since they are actually properties of the global object (window in the browser).

var team = {
  name: 'Jane'
};
var team2 = Object.create(team);
delete team2.name;
console.log(team2.name); // Jane

The result would be “Jane”. Delete operator will not affect prototype property. Here, “name” is a prototype property of team2.

Share

Leave a Reply

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