In Javascript, we have three ways to declare a variable: var, let, const. But did you know that where and how you declare a variable impacts how it behaves because of something called hoisting?
Today, in this blog, we will break it down clearly. Let's start!!!
1. Declaring variables in Javascript
👉 var
+ Function/global-scoped
+ Can be re-declared and updated
+ Hoisted with undefined
👉 let
+ Block-scoped
+ Can be updated but not re-declared in the same scope
+ Hoisted but not initialized
👉 const
+ Block-scoped
+ Cannot be updated or re-declared
+ Must be initialized when declared
2. What is hoisting?
Hoisting is JavaScript's behavior of moving declarations to the top of their scope before execution. This means that variables can be declared after they are used and variables can be used before it has been declared. But not all declarations are hoisted the same way.
3. Hoisting in action
- var: is hoisted and initialized as undefined
- let and const: are hoisted but stay in the Temporal Dead Zone (TDZ) until the line where they’re defined.
4. Temporal Dead Zone (TDZ)
The TDZ is the time between the start of a block and when the let/const variable is declared. Accessing the variable during this period throws a ReferenceError.
5. Function hoisting
- Function declarations are fully hoisted.
Ex:
Ex:
6. Summary
7. Reference
W3schools. JavaScript Hoisting
2 Comments
Nice blog ;)
ReplyDeleteThat means a lot, thank you!
Delete