4

var a = 123;
b = 456;
console.log(window.a, window.b); // 123, 456
delete window.a; // true
delete window.b; // false
console.log(window.a, window.b); // 123, undefined

Why can not delete the global variable if var is not used?

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
msm082919
  • 617
  • 8
  • 24

1 Answers1

11

See the delete operator:

Any property declared with var cannot be deleted from the global scope or from a function's scope.

When you use

b = 456;

the interpreter turns this into

window.b = 456;

that is, an assignment to a property on the window object. But a is different - although it also happens to be assigned to a property on the window object, it is also now a part of the LexicalEnvironment (rather than just being a property of an object) and as such is not deletable via delete.

var a = 123;
b = 456;
console.log(Object.getOwnPropertyDescriptor(window, 'a'))
console.log(Object.getOwnPropertyDescriptor(window, 'b'))

See how the variable declared with var has configurable: false, while the implicit b assignment has configurable: true.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320