Understanding Hoisting in JavaScript with let and const

A Practical Guide to Hoisting Behavior in Modern JavaScript

Max N
3 min readMar 19, 2024
Photo by Thành ‎ on Unsplash

When working with JavaScript, understanding hoisting is crucial for writing clean and bug-free code. Hoisting is a behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase.

In this article, we will explore how hoisting works with the let and const keywords in modern JavaScript, providing clear examples to help you grasp this concept effectively.

What is Hoisting?

Hoisting is a mechanism in JavaScript where variable and function declarations are moved to the top of their containing scope. This means that regardless of where variables are declared in your code, they are hoisted to the top of their function or global scope during compilation.

However, it’s important to note that only the declarations are hoisted, not the initializations.

Hoisting with var vs. let and const

In traditional JavaScript, variables declared with var are hoisted to the top of their scope and initialized with undefined. This can lead to unexpected behavior if variables are accessed before they are declared. However, with the…

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.