consider these slightly two different versions of hoisting...
mylocation = \"dublin\"
function outputPosition() {
alert(mylocation);
mylocation = \"fing
In the second option, you hide mylocation
(which I hope was declared in outer scope.) with a new variable via the var
declaration.
"In JavaScript, variable can be declared after being used." meaning: JavaScript pulls up var
declarations to the top of the scope(No matter where it was declared!), so in your second function var mylocation
is implicitly defined but not assigned before the first alert, hence it output undefined
at that point.
Once you declare variable using var
keyword within a javascript function and no matter where you put this declaration - at the top of the function or at the buttom, it will be considered as local variable. So that is why you get undefined
when you try to get value of such variable before var
declaration.
In JavaScript - variable declarations are hoisted but initialization is not.
That means that when you write var
anywhere inside a function it will be treated as declared in top. So it will not take the same name variable from global space.
@Ashish is right, the first snippet should output "dublin" and "fingal".
The output of first snippet must be "dublin" and "fingal" provided that mylocation is defined,otherwise its a reference error.
For more details :
http://bustingseams.blogspot.in/2009/08/another-javascript-pitfall-hoisting.html
Take for example :
x = 5;
var x;
console.log( x );
Technically you might want to look at x = 5;
as a wrong statement in this context considering the fact that it comes before the declaration, but the JS Engine doesn't work that way. It sees x = 5
and var x
as two separate statements, the first one a compiler-related task, and the second one an execution-related task.
what this means in simple terms is that all declarations in a scope, regardless of where they appear, are processed first before the code itself is executed. i.e you can execute a variable before declaring it.