Monthly Archives: April 2017

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:

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:

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.

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.

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).

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

Share