Notes
Understand them as Lorem Ipsum
JS Interpreter and Execution
Apr 29, 2008Here is a quick (and tricky) mini challenge for those who usually work with javascript. Take a couple of minutes to think about the results of the alerts in each snippet.
// Snippet 1
x = 4;
function init() {
alert(x);
var x = x;
alert(x);
}
init();
// Snippet 2
x = 4;
function init() {
alert(x);
// var x = x;
alert(x);
}
init();
See the answer
.
.
.
The explanation of the behavior of the snippet 1 (undefined, undefined) is that the line var x = x; is doing a declaration var x; and an initialization x = x; at the same time. But each of these processes happen separately, one after the other, when the javascript code is interpreted and then executed.
First, when the code is interpreted, before any code is executed, the var x; declaration makes the variable x available within the scope of the entire function, no matter what line it is written on. It would have the same effect whether var x; was written at the very end of the function or at the very beginning. However, the variable won't be initialized, i.e., assigned to any value, until the code is executed. Until then, its default value will be undefined.
Second, when the code is executed, any x inside that function will refer to the declared local x instead of the global x as one may think at first sight. Therefore, the x = x; initialization won't throw any run time error because the variable x exists but it has never been assigned to any value other than the default undefined.
View all notes...




