What is Hoisting?

Hoisting: Hoisting allows functions and variables(with var) to be used before they are declared. This behavior gives us a peek behind the scenes of how JavaScript works

It's a javascript behavior where function and variable declaration (with Var) are processed before the actual code execution.

it's like a javascript engine taking a sneak peek at our script and setting things up in advance.

Variable Hoisting:

If we only declare variable using var, only the declaration name is Hoisted. It means the variable Exists in the memory before it is assigned a value but the initial value is undefined.

console.log(message) //output: undefined
var message;

If we declare variable using let or const they are not Hoisted in the same way. We cannot use them before their declaration and attempting to do so will throw Reference Error.

console.log(message) // Refrence Error
console.log(secondMessage) // Refrence Error
let message;
const secondMessage = "Good Evening"

Function Hoisting:

Using function keyword these are entirely hoisted to the top of their scope (with function, block, or script ).

So function can be called before their declaration.


sayHi(); // function call
function sayHi() {
 let message = "Hello!";
  console.log(message); // Outputs: Hello! (function declaration is hoisted)
}
0
Subscribe to my newsletter

Read articles from Vikas singh varma directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vikas singh varma
Vikas singh varma

I am a full-stack Developer specializing in MERN, I love simplifying complex topics through writing. Currently seeking job opportunities to enhance my skills and make an impact.