Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 344
msm082919 Avatar asked Dec 18 '22 21:12

msm082919


1 Answers

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.

like image 167
CertainPerformance Avatar answered Dec 28 '22 10:12

CertainPerformance