Search code examples
javascriptdescriptorconfigurable

what is the difference between delete an undefined property and a property which declared by const, let using delete operatorin Javascript?


Please look at the code,

foo = 1;
delete foo; // true
Object.getOwnPropertyDescriptor(this,'foo').configurable // true
var bar = 2;
delete bar; // false
Object.getOwnPropertyDescriptor(this,'bar').configurable // false
const fooBar = 3;
Object.getOwnPropertyDescriptor(this,'fooBar').configurable // undefined
delete fooBar; //false
Object.getOwnPropertyDescriptor(this,'noexist').configurable // undefined
delete noexist; // true

Based on MDN the delete operator can work only with properties where their own descriptor configurable is true, so why there is a difference between delete "fooBar" and "noexist" returned value?


Solution

  • Variables declared with const or let do not get assigned to the global object, hence your

    const fooBar = 3;
    

    does not show up when you do

    Object.getOwnPropertyDescriptor(this,'fooBar').configurable
    

    Only variables declared with var (or never declared at all, only assigned to, such as with foo) get assigned to the global object.

    delete will return:

    true for all cases except when the property is an own non-configurable property, in which case, false is returned in non-strict mode.

    window.foo, having not been declared with var, let, or const, is a configurable property. window.bar, declared with your var bar, is assigned to window as a non-configurable property.

    delete fooBar returns false because fooBar, although not actually a property on window, is a standalone identifier which cannot be deleted - delete will result in false whenever using delete like that would throw an error in strict mode:

    'use strict';
    const someVar = true;
    delete someVar;

    But noexist is not an identifier in your code, so there's no operation to even attempt to perform, so it returns true (and no error would be thrown in strict mode).