Back to Thoughts

Mastering Variable Declarations in JavaScript

Deep dive into JavaScript variable declarations. Understand hoisting, scope, and the critical differences between var, let, and const for bug-free code.


Variable declaration is the first thing we learn in JavaScript, yet it remains one of the most misunderstood topics. Let's break down var, let, and const.

The Contenders

  • var: Function-scoped, can be re-declared, and is hoisted (initialized as undefined).
  • let: Block-scoped, can be updated but not re-declared, and is hoisted (but enters the "Temporal Dead Zone").
  • const: Block-scoped, cannot be updated or re-declared. It must be initialized at declaration.

Hoisting in Action

console.log(x); // undefined
var x = 5;
 
// console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 10;

Recommendation

  1. Use const by default. It makes your code more predictable.
  2. Use let only when you know the variable needs to be reassigned (e.g., in a loop).
  3. Avoid var in modern JavaScript.

By understanding how these keywords interact with the JavaScript engine, you can write cleaner, bug-free code.


© 2026 Daniel Dallas Okoye

The best code is no code at all.