Like Us Like Us Facebook Subscribe Subscribe us YouTube Whatsapp Share us Whatsapp Query Send your queries

JavaScript var vs let vs const: Key Differences Explained

JavaScript var vs let vs const: Key Differences Explained

JavaScript var vs let vs const

If you’ve just started learning JavaScript or you’re diving into modern ES6 code, you’ve definitely seen three different ways to declare a variable: var, let, and const.

At first glance, they all seem to do the same thing—store data. But using the wrong one can lead to silent bugs, crashed apps, or unexpected values in your loops. In this tutorial, we’ll break down the exact differences with simple examples so you know exactly which one to use and when.

JavaScript var vs let vs const

Understanding the Core Keywords: JavaScript var vs let vs const

Before we compare them, let’s quickly define what we’re dealing with. All three are used for variable declaration in JavaScript, but they behave differently based on Scope, Hoisting, and Reassignment.

  • var: The old-school way (pre-ES6). It’s function-scoped and can be tricky.
  • let: The modern, flexible way. It’s block-scoped and preferred for values that change.
  • const: The constant way. It’s block-scoped and cannot be reassigned.

JavaScript Scope Differences: var vs let vs const

Scope determines where your variables are accessible in your code. This is the #1 source of confusion for beginners.

The Problem with var and Global/Function Scope

Variables declared with var are function-scoped. This means if you declare a var inside an if statement or a for loop, it is still available outside of that block.

function runGame() {
  if (true) {
    var score = 100;
  }
  console.log(score); // Output: 100 (Still accessible!)
}
runGame();

This behavior often leads to accidental “variable leaking” where temporary values pollute the rest of your function.

The Solution with let and const (Block Scope)

Both let and const are block-scoped. A block is anything between two curly braces { }. Once the block ends, the variable disappears.

function runGame() {
  if (true) {
    let lives = 3;
    const maxLives = 5;
  }
  console.log(lives); // ❌ Error: lives is not defined
}
runGame();

Why this matters: Using let in a for loop ensures the variable i doesn’t hang around after the loop finishes, preventing memory leaks and naming conflicts.

Reassignment and Mutation Rules

Using var and let for Mutable Values

You can declare a variable with var or let without a value and update it as many times as you want.

var age = 25;
age = 26; // ✅ Allowed

let name = "Sam";
name = "Alex"; // ✅ Allowed

The Immutability of const (But Not Quite!)

This is a huge misconception. const does NOT mean the value is immutable (unchangeable). It means the binding is immutable. You cannot use the = sign to reassign a const variable.

const birthYear = 1995;
birthYear = 1996; // ❌ TypeError: Assignment to constant variable.

However, when dealing with Objects and Arrays, you can change the contents of a const variable:

const user = { name: "John", id: 1 };
user.name = "Jane"; // ✅ This is FINE (Modifying object property)

const colors = ["red", "blue"];
colors.push("green"); // ✅ This is FINE (Modifying array)

Pro Tip: Use const by default. Only use let when you know the variable’s pointer needs to change (like a counter in a loop).

Hoisting Behavior Explained with Examples

Hoisting is JavaScript’s default behavior of moving declarations to the top of their scope during compilation. However, how they are initialized differs.

KeywordHoisted?Initialized ValueCan Access Before Line?
varYesundefinedYes (But it’s undefined)
letYesNot Initialized (TDZ)❌ ReferenceError
constYesNot Initialized (TDZ)❌ ReferenceError

Hoisting with var (Risky)

Because var is initialized as undefined, you can technically log it before the line it’s written on. This is rarely what you want.

console.log(oldCar); // Output: undefined (No Error - Weird!)
var oldCar = "Honda";

The Temporal Dead Zone (TDZ) for let and const

The TDZ is the time between entering the scope and the actual line where let/const is declared. Accessing the variable in this zone throws a ReferenceError.

console.log(newCar); // ❌ ReferenceError: Cannot access 'newCar' before initialization
let newCar = "Tesla";

Takeaway: let and const force you to write cleaner, more predictable code by preventing use-before-declaration.

JavaScript var vs let vs const: A Quick Comparison Table

Featurevarletconst
ScopeFunction / GlobalBlock {}Block {}
Reassignable✅ Yes✅ Yes❌ No
Redeclarable✅ Yes (Bad)❌ No❌ No
HoistingYes (undefined)Yes (TDZ Error)Yes (TDZ Error)
Best Use CaseLegacy Code OnlyLoop Counters / Mutable DataConstants / Objects / Functions

Best Practices: Which One Should You Use in 2026?

If you’re writing modern JavaScript (ES6+), here is the golden rule followed by most professional developers and the Airbnb Style Guide:

  1. Start with const. Always default to const when creating a new variable. It signals to other developers that this variable binding won’t be re-assigned.
  2. Use let when you must change it. If you have a loop counter (let i = 0) or a variable that needs to be updated over time, switch to let.
  3. Avoid var entirely. There is almost no reason to use var in new code unless you are supporting Internet Explorer 10 or writing very specific legacy glue code.

Example Scenario: Building a User Profile

// Correct usage of const and let
const API_URL = "https://api.codentricks.com/users"; // Never changes -> const
const userData = { name: "Guest" }; // Binding never changes -> const

let loginAttempts = 0; // Number will change -> let
let isLoading = true; // Boolean will change -> let

function fetchUser() {
  if (true) {
    let tempId = 12345; // Only needed inside this block -> let
    console.log(tempId);
  }
  // tempId is gone here (good!)
}

Conclusion

The difference between var, let, and const boils down to scope and reassignment. While var was the original workhorse, its lack of block scope created too many bugs in large applications. By mastering let and const, you’ll write JavaScript that is cleaner, safer, and much easier to debug.

You may also interested in learning JavaScript Calculator

If you have and query or suggestion or need assistance then please contact me using comments, I will reply to fix your problem, if you like our content then you can subscribe to our Youtube channel. If you want to hire me then reach us at info@codentricks.com.

5 1 vote
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments