This piece of code did not do what I expected, can you tell?
// define a var
x = 1;
function changex() {
console.log(x); // I expect this to print 1
var x = 2; // define a local var x
console.log(x); // I expect this to print 2
}
changex();
What do I actually get?
undefined
2
Why the heck is x undefined for the first print? it turns out javascript does what is called "hoisting" meaning it collects all local variable definitions in one place before executing any function code. therefore the function is effectively doing this
var x; // undefined
console.log(x); // prints undefined
x=2;
console.log(x); // prints 2
This really got me the first time I read this
References: Javascript patterns, Stoyan Stefanov
// define a var
x = 1;
function changex() {
console.log(x); // I expect this to print 1
var x = 2; // define a local var x
console.log(x); // I expect this to print 2
}
changex();
What do I actually get?
undefined
2
Why the heck is x undefined for the first print? it turns out javascript does what is called "hoisting" meaning it collects all local variable definitions in one place before executing any function code. therefore the function is effectively doing this
var x; // undefined
console.log(x); // prints undefined
x=2;
console.log(x); // prints 2
This really got me the first time I read this
References: Javascript patterns, Stoyan Stefanov
Comments
Post a Comment