'Hoisting in javascript along with global variable
The below code gives an output of undefined
. I was of the impression that all variable and function declarations are hoisted to the top of their scope and so b
should now be at the top the scope before calling a()
. However, I still get undefined
as my output?
a()
var b = 5;
function a() {
console.log(b)
}
Solution 1:[1]
You misunderstand how hoisting works. It doesn't hoist the assignment, it only hoists the declaration. Your code is equivalent to the following:
var b; // undefined
function a(){
console.log(b)
}
a();
b = 5;
Solution 2:[2]
Yes the variable declaration is hoisted, but the value is not set on b
. The code looks like this
var b
function a(){
console.log(b)
}
a()
b = 5;
Solution 3:[3]
Hoisting means the variables will be created “at the top” - but it does not change anything about the time the value assignment happens, the b = 5
part still happens when execution reaches the part where it’s written. So if you call a()
before that, b
exists, but has not gotten any value assigned yet … hence, undefined
Solution 4:[4]
You are using a function declaration to create a function. So function declaration is also hoisted so they are being used before declaring.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jared Smith |
Solution 2 | |
Solution 3 | 04FS |
Solution 4 | zshan4444 |