Confused about hoisting

こ雲淡風輕ζ 提交于 2019-12-01 22:34:54

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 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.

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

shikhar chauhan

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".

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!