Question
I'm trying to understand why the following three JavaScript examples produce different outputs, even though they all seem to involve function hoisting. Shouldn't the outputs be the same based on how function hoisting works?
Example 1
var a = 0;
console.log("1 a:", a);
if(true){
a = 1;
function a() {}
a = 5;
console.log("2 a:", a);
}
console.log("3 a:", a);
The output is:
1 a: 0
2 a: 5
3 a: 1
This has been verified.
Example 2
var a = 0;
console.log("1 a:", a);
if(true){
a = 1;
a = 5;
console.log("2 a:", a);
function a() {}
}
console.log("3 a:", a);
The output is:
1 a: 0
2 a: 5
3 a: 5
This has been verified.
Example 3
var a = 0;
console.log("1 a:", a);
if(true){
function a() {}
a = 1;
a = 5;
console.log("2 a:", a);
}
console.log("3 a:", a);
The output is:
1 a: 0
2 a: 5
3 a: f a() {}
This has been verified.
What I've Tried
I've read up on function hoisting in JavaScript, but these examples are throwing me off. I'm not sure why they don't produce the same output based on my understanding of function hoisting.
Questions
- How do these examples differ in the context of function hoisting?
- Why is the output different in each example?
Any insights would be much appreciated!