Just "Hoist"

Just "Hoist"

ยท

2 min read

Hoisting is one of the well none as well as one of the jargon words in JS. But It's not because of the way it was just because the how deeply your trying to understand it.

Before writing this I do have the same perception about hoisting. So, to make things super easy just stay with me atleast 2min. I bet you won't regret.

Before jump in just keenly understand the Python & JavaScript code

print(a) # NameError name 'a' is not defined
a = 10
console.log(a) //undefined
var a = 10

It's as simple as it is. Yes you got it right

In JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables, classes, or imports to the top of their scope, prior to execution of the code.

It only hoists declaration not initialization. That's why in the code we get result as 'undefined' not '10'

So, If your are worrying how javascript storing undefined rather than any garbage value then I will highly recommend to see js ExecutionContext video.

The same applicable for functions as well. But if everything works fine this much we can't say it as JavaScript right!!๐Ÿ˜‚

For that

look the code below

console.log(a) //Uncaught ReferenceError: Cannot access 'a' before initialization
console.log(b) //Uncaught ReferenceError: Cannot access 'b' before initialization
const a = 10
let b = 20

Even though both the a, b are variables they are trowing errors this is because we declare them with const & let keywords.This is the error for the class as well, But why???๐Ÿค”

Because the temporal dead zone strictly forbids any use of the variable before its declaration.

At the end it's just the one of the behaviors of javascript but it's important to understand how it works to avoid unexpected behavior in your code.

Did you find this article valuable?

Support Malavi Pande by becoming a sponsor. Any amount is appreciated!

ย