ref – https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var
Declared variables are constrained in the execution context in which they are declared.
Undeclared variables are always global
1 2 3 4 5 6 7 8 9 |
function x() { y = 1; // Throws a ReferenceError in strict mode var z = 2; } x(); console.log(y); // logs "1" console.log(z); // Throws a ReferenceError: z is not defined outside x |
…even in inner functions
Let’s declare an inner function called ‘inner’. We have an undeclared variable ‘name’.
That name will be declared as a global. It will be accessible by all scopes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// name is declared globally, thus can be accessed by all scopes function x() { console.log('-- x -- '); y = 1; // Throws a ReferenceError in strict mode var z = 2; function inner() { console.log('-- inner --'); name = 'ricky'; } inner(); console.log(name); // ricky } x(); console.log(y); // logs "1" console.log(name); // ricky console.log(z); // Throws a ReferenceError: z is not defined outside x |