JS shadowing


Simple script to display the overriding of variables through scoping... it's called shadowing. You're creating two vars by the same name, yet the second one does not destroy the first one, neither is it the same (which is usually the case in JS).

var x = 6;
var x = 7;

In the previous example, x is not redefined or destroyed. The second var keyword is simply ignored.

var x=5,y;
var x = 6;
y = x;

This will alert "5,7". The assignment to x in the inner function is set to a second version of x. The top x is not changed in this process. The value of the inner x is assigned the top y. So after all the functions have ran, x remains 5 and y will be 7.

The "danger" in this is that the outer x is inaccessible to you. On the other hand, it could help you to create a safe environment where executing code cannot possibly reach certain data.