Explain the concept of "hoisting" in JS. How does it affect variable and function declarations?
143
17-Jun-2024
Updated on 17-Jun-2024
Ravi Vishwakarma
17-Jun-2024JavaScript 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, before execution of the code.
Variable Hoisting:
When you declare a variable using
var
orlet
, the declaration is hoisted to the top of its scope. Here's how hoisting affects variables:After hoisting, the code behaves like this:
Function Hoisting:
Function declarations are fully hoisted, including both the function name and its body. This allows you to call a function before its actual declaration in the code.
After hoisting code like this
After hoisting code behaves like this.