Understanding JavaScript Hoisting: A Beginner’s Guide
Hoisting in JavaScript is a default behavior in which a function or a variable can be used before declaration.

Consider a theater play where an actor walks on stage before being introduced. It’s confusing for the audience. In JavaScript, something similar can happen with variables.

console.log(name); // undefined
var name = "Alice";

The variable name is printed before it’s even defined. What’s going on? In JavaScript, the declarations of variables (using var) are moved, or “hoisted”, to the top of their scope. So the computer reads the code like this:

var name;
console.log(name); // undefined
name = "Alice";

It’s as if the actor walks on stage, and only then we learn their name.

But this doesn’t happen with variables declared using let or const. So remember, it’s unique to var.

In JavaScript, you can call a function before it’s even defined in the code. That’s because functions are also hoisted. They’re ready to be called from the get-go.

console.log(sing()); // "La la la"
function sing() {
  return "La la la";

In JavaScript, Hoisting is the javascript default behavior of moving all the declarations (function and variables) at the top of the current scope before code execution.


Leave a Comment