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()
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()
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();
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.