What is the difference between using var and not when declaring a variable?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


What is the difference between using var and not when declaring a variable?




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?




1 Answer
1



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.


window


a


window


LexicalEnvironment


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.


var


configurable: false


b


configurable: true






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Makefile test if variable is not empty

Will Oldham

Visual Studio Code: How to configure includePath for better IntelliSense results