简体   繁体   中英

Hoisting in javascript

I asked a question before and somebody give me a guide and I read it and I saw this

  var temp = setTimeout,
  setTimeout = function() {};

He said that temp will be undefined due to JavaScript hoisting and I dont understand why Its not should be like that?

    var temp;
    temp = setTimeout;
    setTimeout = function() {};

so why its undefined?

This is not the same. Your multiple var declaration also declares setTimeout :

var temp = setTimeout,
    setTimeout = function() {};

which is hoisted to

var temp; // = undefined
var setTimeout; // = undefined
temp = setTimeout;
setTimeout = function() {};

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,

var a; //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 = undefined
console.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 = undefined
var setTimeout; // setTimeout = undefined
temp = setTimeout; // here temp is undefined as setTimeout is undefined
setTimeout =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:

medium: what is javascript hoisting

scotch: understand hoisting in javascript

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM