What is hoisting in Javascript?

Hoisting is a concept in JavaScript where variable and function declarations are moved to the top of their respective scopes during compilation phase.

This means that, in JavaScript, you can use a variable or function before it has been declared, and it will still work.

Variable Hoisting

In JavaScript, variables can be declared using the var keyword. If you declare a variable using var, its declaration is hoisted to the top of its scope, but its value is not initialized until its assignment statement is executed.

For example:

console.log(myVar); // undefined
var myVar = 10;
console.log(myVar); // 10

Even though myVar is logged before its assignment statement, it is still declared at the top of its scope and therefore its value is undefined. The value of myVar is only assigned later when the assignment statement myVar = 10 is executed.

Function Hoisting

Function hoisting is similar to variable hoisting, except that function declarations are fully hoisted, including their definitions.

For example:

myFunction(); // "Hello World"
function myFunction() {
  console.log("Hello World");
}

In this example, the function myFunction() is called before it is defined. However, because function declarations are fully hoisted, the code still runs as expected and logs “Hello World” to the console.

Variable declaration using let and const keywords:

Unlike var declarations, let and const declarations are not hoisted. If you try to access a let or const variable before it is declared, you will get a ReferenceError.

console.log(var1); // ReferenceError: var1 is not defined
let var1 = 10;

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: