Why variable hoisting after return works on some browsers, and some not?

前端 未结 5 1108
执笔经年
执笔经年 2020-11-22 12:11
alert(myVar1);
return false;
var myVar1;

Above code throws error in IE, FF and Opera stating that return statement has to come in the function. But

5条回答
  •  孤街浪徒
    2020-11-22 12:47

    Sometimes hoisting is explained in a way which may give wrong impression, i.e. the variables and functions are hoisted by JavaScript engine as if they were physically moved on top, which is not actually right, as demonstrated by the code below:

    console.log(a);
    var a = 'Hello World!';
    

    What we see on console is undefined, not 'Hello World', so we got the behavior of the following code

    var a;
    console.log(a);
    a = 'Hello World!';
    

    not the behavior of

    var a = 'Hello World!';
    console.log(a);
    

    which you may get the impression from the variables and functions declaration being moved to top statement.

    But JavaScript is not actually moving your code anywhere. You need to understand execution context in JavaScript. It has two phases creation phase and execution phase. In creation phase memory space is created for these variables and functions, and people seem to confuse this step with hoisting. JavaScript is actually not moving your code anywhere, what happens is JavaScript has created memory space for all your code i.e. variables and functions, functions can be placed fully in memory but in case of variables the assignments are processed in execution phase of the execution context. So when you do var a = 'Hello World!', JavaScript engine knows the value of a when it starts executing it in execution phase of execution context, so it puts a placeholder undefined, and all variables are initially set to undefined in JavaScript. So it is not good to rely on hoisting and see undefined. So it is always good to declare variables and functions on top of your code.

提交回复
热议问题