πŸ”« The Three Musketeers: var, let, and const

K ManojK Manoj
4 min read

πŸ”Ά Introduction

In the world of JavaScript, declaring variables is one of the most fundamental concepts every developer must master. Whether you're storing a user's name, calculating a shopping cart total, or managing application state, variables are the building blocks that hold your data. Now, these Variable Declarations are statements which tell the JavaScript engine to reserve memory space for storing data. Visualize them as labels or containers that hold values you want to use throughout your program. But JavaScript offers three different ways to declare variables: var, let, and const – each with its own personality, rules, and best use cases.

Below is the basic syntax on how to create Containers in-order to store different types of data.

var userName = "John";
let userAge = 22;
const userMail = "john@hashnode.com";

πŸ›οΈ var: The Veteran

var is the original and old way to declare variables in Javascript dating back to the 1995 when the language was taking it’s place. It's the grandfather of variable declarations – reliable, but with some quirks that can surprise modern developers.

πŸ†• let: The Modern Alternative

Introduced in ES6 (2015), let was designed to solve many of the issues developers encountered with var. It's the modern, block-scoped way to declare variables that can change.

πŸ’‘
ES6 stands for ECMAScript 6. It is a JavaScript standard intended to ensure a common language across different browsers.

πŸ”’ const: The Immutable Guardian

Also introduced in ES6, const is for declaring variables that should never be reassigned. It's perfect for values that remain constant throughout your program's execution.

πŸ“¦ Scope Difference

var

  • Function-scoped – visible throughout the entire function where it is declared.

  • Not block-scoped, so accessible even outside if, for, or {} blocks.

let & const

  • Block-scoped – confined to {} blocks like if, for, while, or functions.
{
        var a = 5;
        let b = 10;
        const c = 15;
}

console.log(a); // 5
console.log(b); // ReferenceError
console.log(c); // ReferenceError

🎈 Hoisting Behaviour

  • var is hoisted to the top of its scope and initialized with undefined.

  • let and const are also hoisted but stay in a temporal dead zone until their declaration is reached.

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

console.log(y); // ReferenceError
let y = 10;
πŸ’‘
In traditional programming languages, a function must be defined before it can be called. However, in JavaScript, the function can be called before it is defined. This behavior is known asΒ hoisting, and it's a fundamental aspect of how JavaScript works.

Note: We will explore more about hoisting in a later blog, for now this explanation is enough.

πŸ“ Re-declaration Rules

  • var: Can be re-declared and updated in the same scope.

  • let: Cannot be re-declared in the same scope but can be updated.

  • const: Cannot be re-declared or updated.

var a = 5;
var a = 10; // βœ…

let b = 20;
let b = 2; // ❌ SyntaxError -> since updated in the same scope

const c = 100;
const c = 1; // ❌ SyntaxError

🧬 Mutability

const prevents reassignment, not mutability. Objects/arrays declared with const can still be modified.

const obj = { key: 'value' };
obj.key = 'newValue'; // βœ… allowed

obj = {}; // ❌ TypeError

🌍 Global Object Binding

  • var declarations attach to the global object (window in browsers).

  • let and const do not.

var x = 100;
let y = 200;

console.log(window.x); // 100
console.log(window.y); // undefined

🏠 Real-World Analogy

Think of variable declarations like different types of storage containers:

  • var: Like a cardboard box that can be moved anywhere in the house, relabeled, and its contents changed

  • let: Like a labeled drawer that stays in its room, can have its contents changed, but can't be relabeled

  • const: Like a sealed safe that stays in its room, can't be moved, relabeled, or have its lock changed (though you might organize what's inside)

βœ… Best Practice

  • Use let for variables that change.

  • Use const for constants or references that don’t change.

  • Avoid var – it leads to confusing bugs due to scope leakage and hoisting quirks.

⚠️ Common Pitfalls

Let’s see what happens when we use var inside loops with closures.

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1000); // prints 3, 3, 3
}

But if we use let instead, let’s look at how the output changes.

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1000); // prints 0, 1, 2
}

🎯 Conclusion

Understanding the differences between var, let, and const is more than just knowing syntax – it's about writing cleaner, more predictable, and bug-free JavaScript code. As we've explored throughout this blog, each declaration type serves a specific purpose and comes with its own set of rules that can make or break your application.

The choice between var, let, and const might seem small, but it's these fundamental decisions that separate good developers from great ones.

Happy coding, and may your variables always be properly scoped! πŸš€

1
Subscribe to my newsletter

Read articles from K Manoj directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

K Manoj
K Manoj

Backend Web Developer | Security Enthusiast |