JavaScript hoisting for multiple declarations of the same variable

点点圈 提交于 2019-12-11 10:49:53

问题


I was trying to understand JavaScript hoisting and from what I have understood, memory space is set aside for all the variable declarations before the execution of the code.

I would like to understand how the interpreter works through hoisting in case of multiple declarations for the same variable. Consider the following code:

 console.log(a);

 //first declaration
 function a() {
     console.log('hello');
 }

 //second declaration
 var a = 2;

The output is the function declaration:

function a() {
    console.log('hello');
}

So, I am assuming the first declaration the interpreter encounters is the one which is stored in memory. However, changing the order of declarations to:

console.log(a);

//first declaration
 var a = 2;

//second declaration
function a() {
    console.log('hello');
}

results in the same output! The interpreter ignores the first declaration and stores the second declaration in memory. Why is this happening? Shouldn't the output in the second case be undefined?


回答1:


Your code will be read by the interpreter like below,

 function a() {
     console.log('hello');
 }
 var a;
 console.log(a);
 a = 2;

so while executing the above code, a will be referring the function initially and after that var a; line will be executed, since a is undefined there, an assigned value will not be set with undefined by means of a variable declaration. Hence that line got ignored and printing the primitive value of the function reference.

A simple example for your better understanding would be,

function x(){  };
var x;
console.log(x); //function x(){  }


来源:https://stackoverflow.com/questions/36246543/javascript-hoisting-for-multiple-declarations-of-the-same-variable

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