1

Why typeof of b is undefined in the below code?

var b = function() {}

var a = function() {
var b = b
console.log('typeof function_b:', typeof b) 
}
a()
shadowfox
  • 581
  • 1
  • 7
  • 20
  • 1
    You can choose the dup: https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript https://stackoverflow.com/questions/111102/how-do-javascript-closures-work ... – Andreas Louv May 24 '16 at 19:29

2 Answers2

2

Because you're initialising a new variable inside the a function scope with the declaration var b.

var b gets initialised and ran before the value gets assigned (b = b), so it is assigning the just-initialised empty value to itself.

To alter the output, you can just skip the var declaration and typeof b outputs "function":

var b = function() {}

var a = function() {
    b = b;
    console.log('typeof function_b:', typeof b); // Outputs "function"
}
a();
jehna1
  • 3,110
  • 1
  • 19
  • 29
0

That's because the variable first get declared (var b), and then assigned b = b. After declaring it, it is undefined in that scope, so you're assigning undefined to it.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177