Europe/Helsinki
BlogSeptember 26, 2025

JavaScript: let vs const vs var — When Should You Use Each?

Thang Ngo
Choosing between let, const, and var affects variable scope, the errors you may encounter (such as hoisting and the TDZ), and how your code communicates your intent. This article explains the differences and provides clear rules for choosing the right declaration. In JavaScript, there are three main ways to declare variables: var, let, and const. They differ as follows:
  • const
    • Has block scope, meaning it is only accessible within the block where it is declared.
    • Cannot be reassigned to a new value, although objects and arrays can still be modified.
    • Is hoisted but cannot be accessed before its declaration because of the TDZ.
    • ✅ The best choice for most variables. Use it by default.
  • let
    • Also has block scope.
    • Can be reassigned to a new value.
    • Is also affected by the TDZ.
    • ✅ Use it when you need to change a variable's value.
  • var
    • Has function scope, or global scope when declared outside a function.
    • Can be reassigned and redeclared within the same scope.
    • Is hoisted and initialized to undefined, so it does not have a TDZ.
    • ⚠️ Avoid it in modern JavaScript because it can cause confusing bugs.
Block scope means a variable is only accessible within the { ... } block where it is declared, such as in if/else, for, and try/catch blocks. Function scope means a variable is accessible throughout the function in which it is declared. A var declaration outside a function has global scope in a classic script, but its behavior differs in ES modules.
Js
if (true) {
  const a = 1;
  let b = 2;
  var c = 3;
}

console.log(typeof a); // "undefined"
console.log(typeof b); // "undefined"
console.log(c);        // 3
  • a and b are block-scoped, so they cannot be accessed outside the if block. Using typeof on these inaccessible identifiers returns "undefined" in this example.
  • c is declared with var, so it is accessible outside the block.
Note that directly accessing a or b with console.log(a) or console.log(b) would throw a ReferenceError.
All three declarations are hoisted, but they behave differently.
  • var is hoisted and initialized to undefined.
  • let and const are hoisted but remain uninitialized until their declarations are evaluated.
  • The period between entering the scope and evaluating a let or const declaration is called the Temporal Dead Zone (TDZ).
Accessing a let or const variable during the TDZ causes a ReferenceError.
Js
console.log(a); // undefined
var a = 1;

console.log(b); // ReferenceError
let b = 2;

console.log(c); // ReferenceError
const c = 3;
JavaScript processes declarations before executing the code in their scope. However, let and const cannot be accessed until their declarations have been evaluated. This is why using let and const helps catch certain programming mistakes earlier.
One common misconception is that const makes a value completely immutable. In reality, const prevents reassignment of the variable, not modifications to the contents of an object or array.
Js
const user = { name: "Alex" };
user.name = "Christian"; // Allowed: modifies the object
user = { name: "New" };  // TypeError: reassignment is not allowed

let count = 0;
count += 1; // Allowed: let permits reassignment
The user variable still references the same object after user.name changes. However, assigning a different object to user is not allowed. If you want to prevent changes to an object's own properties, you can use Object.freeze().
Js
const config = Object.freeze({
  retries: 3,
});

// In strict mode, this throws a TypeError.
// In non-strict mode, the assignment is silently ignored.
config.retries = 5;

console.log(config.retries); // 3
Important: Object.freeze() is shallow. Nested objects can still be modified unless they are frozen separately.
When using var in a loop, all iterations share the same variable. If asynchronous callbacks access that variable later, they may all observe its final value. Using let creates a new binding for each iteration of the loop.
Js
// ❌ Using var: outputs 3, 3, 3
var buttons = [0, 1, 2];
for (var i = 0; i < buttons.length; i++) {
  setTimeout(() => console.log(i), 0);
}

// ✅ Using let: outputs 0, 1, 2
for (let j = 0; j < buttons.length; j++) {
  setTimeout(() => console.log(j), 0);
}
Why does this happen? The callbacks execute after the loop finishes. With var, they all reference the same i, whose final value is 3. With let, each iteration has its own binding, preserving the expected value. Accessing a variable before its declaration has been evaluated causes a ReferenceError.
Js
{
  // console.log(greet); // ❌ ReferenceError (TDZ)
  const greet = "hello";
  console.log(greet); // ✅ "hello"
}
Best practice: Declare variables before using them, and keep declarations close to where they are needed. var allows redeclaration within the same scope, which can lead to accidental overwrites. let and const do not allow redeclaration in the same scope.
Js
var x = 1;
var x = 2; // ✅ Allowed, but potentially dangerous

let y = 1;
// let y = 2; // ❌ SyntaxError

const z = 1;
// const z = 2; // ❌ SyntaxError
Using let and const helps JavaScript catch duplicate declarations before execution.
Use const by default to communicate your intent clearly: the variable should not be reassigned.
Js
const BASE_URL = "https://api.example.com";

const headers = {
  "Content-Type": "application/json",
};
This makes the code easier to understand and prevents accidental reassignment. Use let when the variable needs to hold different values over time, such as counters, accumulators, or values updated inside loops.
Js
let attempts = 0;

while (attempts < 3) {
  // Perform some work
  attempts++;
}
Here, let is appropriate because attempts changes with each iteration. For new code, prefer const and let. They provide more predictable scoping rules and help prevent common bugs. When working with legacy code, keep in mind that changing var to let or const can affect behavior. Test the changes carefully, especially when closures, loops, or global variables are involved.
  • Use const by default.
  • Use let when reassignment is necessary.
  • Avoid var in new code to reduce scope-related bugs.
  • Remember the TDZ: do not access let or const variables before their declarations are evaluated.
  • Remember that const prevents reassignment, not modifications to objects or arrays.
  • Use Object.freeze() when you need to prevent changes to an object's own properties, keeping in mind that it is shallow by default.
Happy coding! 🚀
Share this post:

Comments

No comments yet. Be the first to share your thoughts.

Leave a comment

Comments are reviewed before they are published.
On this page