DEV Community

Gayathri.R
Gayathri.R

Posted on

Understanding Hoisting: How JavaScript Handles Declarations

Example 1: Variable Hoisting with var

console.log(x); // Output: undefined
var x = 10;
Enter fullscreen mode Exit fullscreen mode

Explanation:

JavaScript hoists the declaration of x to the top (var x;), but not the value.

So it's as if you wrote:

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

Enter fullscreen mode Exit fullscreen mode

But let and const do NOT hoist like var

console.log(y); // ReferenceError
let y = 5;

Enter fullscreen mode Exit fullscreen mode

Example 2: Function Hoisting

greet(); // Output: Hello!

function greet() {
console.log("Hello!");
}

Explanation:

The entire function greet() is hoisted to the top.**

Top comments (1)

Collapse
 
vic_xie_9bed0062d5fd73d12 profile image
vic xie

Nice write-up! For devs who deal with messy copied text, TextStow might help — it's a Mac menu bar tool combining clipboard history with prompt templates and text cleanup. Free: textstow.com