Confused about hoisting

前端 未结 5 1439
感情败类
感情败类 2021-01-21 03:09

consider these slightly two different versions of hoisting...

mylocation = \"dublin\" 
function outputPosition() {
    alert(mylocation);
    mylocation = \"fing         


        
相关标签:
5条回答
  • 2021-01-21 03:26

    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.

    0 讨论(0)
  • 2021-01-21 03:35

    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.

    0 讨论(0)
  • 2021-01-21 03:38

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

    0 讨论(0)
  • 2021-01-21 03:40

    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

    0 讨论(0)
  • 2021-01-21 03:47

    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.

    0 讨论(0)
提交回复
热议问题