Since scope in JavaScript is a functional object. When you execute some code in a function (your code sample), alert (x) will find if there is any definition of "x" in the function. So, in this function there is "var x = 2". But JavaScript runtime will explain your code as follows:
x = 1;
alert(x);
var y = function() {
var x;
alert(x);
x = 2;
alert(x);
}
y();
So, x in the second warning is "undefined", not "1". Therefore, when you declare a variable in a function, I recommend that you declare variables at the top of your function.
source
share