Scope
Shadowing (Variable Shadowing)
Having two variables at different scopes of the same name is called shadowing
Variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. This outer variable is said to be shadowed.
Line 1 will be shadowed by line 3 in given examples.
Automatically Global variables (Implicit Global variable - Undeclared variable)
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
Line 5 will not throw an error. Instead it will create a global variable called
bar
. Note that it is not created in function's scope instead it's inside global
scope.
This will only happen in non-strict mode. Strict mode will prevent this feature.
Historically Javascript tried to be as forgiving as possible. This is the reason behind automatic global variable.
In HTML, the global scope is the window object. Because of that bar
will
attach it self to window object.
Strict mode
Strict mode makes it easier to write "secure" JavaScript.
Strict mode changes previously accepted "bad syntax" into real errors.
As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.
In "Strict Mode", undeclared variables are not automatically global. Line 4 will
throw a ReferenceError