Hoisting In Javascript
Solution 1:
This is not the same. Your multiple var
declaration also declares setTimeout
:
var temp = setTimeout,
setTimeout = function() {};
which is hoisted to
var temp; // = undefinedvarsetTimeout; // = undefined
temp = setTimeout;
setTimeout = function() {};
Solution 2:
The scope of a variable declared with the keyword var is its current execution context. When a variable is initialized, javascript engine by default initializes the variable to undefined. Like,
vara; //it initializes to undefined
Again when you use a variable before declaring them, its now on running context. For Example:
console.log(a);
var a=10;
in this case, javascript engine runs the code in following ways,
var a; // a = undefinedconsole.log(a); //
a =10;
it pick up the variable declaration to the top of the execution context but not its value. This is called hoisting that you have already probably known.
In your case:
var temp = setTimeout,
setTimeout = function() {};
from function(){}, suppose we get value =10;
now your code seems like:
var temp = setTimeout,
setTimeout = 10;
but javascript does the thing in the following way,
var temp; // temp = undefinedvarsetTimeout; // setTimeout = undefined
temp = setTimeout; // here temp is undefined as setTimeout is undefinedsetTimeout =10;
it keep up all declared variable to the top of stack (Not its value but initializes to undefined).
If you want to learn more, visit the following link:
Post a Comment for "Hoisting In Javascript"