5

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?

David G
  • 94,763
  • 41
  • 167
  • 253
user1801625
  • 1,153
  • 3
  • 13
  • 14
  • 3
    To anyone answering, note the comma in the first block of code after "setTimeout". +1 – jamesmortensen Nov 22 '12 at 02:28
  • It's not really clear to me what you're asking. `temp` is declared and then initialized to the undefined value `setTimeout` before `setTimeout` is declared and defined. But defining `setTimeout` also sounds like a really bad idea, at least in a browser environment, as that is a symbol already used. – Scott Sauyet Nov 22 '12 at 02:33

2 Answers2

5

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() {};
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

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