The weird delete operator in JavaScript

  • 2020-05-16 06:17:19
  • OfStack

The operator delete is not very common in javascript, but it does have some weird features.

1. Delete the properties of the object.


var o = {
    a: 1,
    b: 2  
};
delete o.a;
alert(o.a);  //undefined

So, whether delete deleted the property of the object or the property value of the object, I began to think that it should be the value deleted, because the result is undefined, and no error was reported. But in fact, I was wrong. For example:


var o = {};
var a = {
    pro: "zhenn"
};
o.c = a;
delete o.c;    // Delete the object o The properties of the a
console.log(o.c);     // undefined
console.log(a.pro);   // zhenn

From the above code, it is not difficult to see that after delete o.c, the value pointed to by o.c has not been deleted, that is, the object a still exists, otherwise a.pro should not be able to pass the compilation. With that said, when delete deletes an object's properties, it removes the reference to the property value in the object, but the value is still on the object stack!

2. Operation on the array, first look at the code:


var arr = [1,2,3];
delete arr[2];
console.log(arr.length);  // 3
console.log(arr);   // [1,2,undefined]

Again, delete did not actually delete the element, just the key value corresponding to the element. In order to further understand the nature of delete, compare it with the pop method in Array. As follows:


var arr = [1,2,3];
arr.pop();
console.log(arr);  // [1,2]
console.log(arr.length)  // 2

This should bring the truth to light.

3. The above operations on objects and arrays are easy to understand, but the operations on variables are hard to understand. The code is as follows:


var a = 1;
delete a;
alert(a); // 1
 
function fn(){ return 42; }
delete fn;
alert(fn());  // 42
 
b = 2;
delete b;
alert(b);  // b is not defined;

It is difficult to explain it, because it is also a global variable, the variables declared by var cannot be deleted, while the variables directly declared by b can be deleted, which is weird. In the explanation given by ECMA, it only means that the variables declared by var and the functions declared by function have DontDelete characteristics and cannot be deleted.


Related articles: