I've recently been delving into some documentation and have noticed some inconsistencies in hoisting patterns within JavaScript.
Consider the following examples:
When it comes to functions,
function abc(){
console.log("worked")
}
abc();
OUTPUT : worked
In contrast,
abc();
function abc(){
console.log("worked")
}
OUTPUT : worked
This behavior is due to hoisting, where memory space is reserved for 'abc' at the start of execution context.
However, this doesn't hold true for variables, leaving me pondering why.
For instance,
var a = "Hello"
console.log(a)
OUTPUT : Hello
**Then why the difference in the example below?
console.log(a)
var a = "Hello"
The above code results in "undefined"
As the script runs:
- 'a' is initialized as undefined first
- Following that, it gets reassigned to the value "Hello"
Despite this, the output still reads undefined
Any insights on this discrepancy would be greatly appreciated. Thank you for your time.