JavaScript var vs let vs const: The Complete Guide for Beginners (2026)
Introduction: Why Variable Declaration Matters
Have you ever started learning JavaScript and felt confused about when to use var, let, or const? You're not alone.
I remember my first JavaScript project. I declared every variable with var because I didn't know better. Then my code broke in mysterious ways. Values changed unexpectedly. Variables appeared where they shouldn't exist.
Sound familiar? Here's the truth: Understanding JavaScript variable declarations is like learning the traffic rules before driving. You might move forward without them, but you'll crash eventually.
In this comprehensive guide, I'll break down var vs let vs const in the simplest way possible. No jargon. No confusion. Just practical knowledge you can use today.
By the end of this article, you'll know exactly which declaration to use and why. Let's dive in.
What Are Variables in JavaScript?
Before we compare var, let, and const, let's understand what variables actually are.
Think of a variable as a labeled box where you store information. Just like you might have a box labeled "toys" in your room, JavaScript variables are containers with names that hold data.
Here's a simple example:
javascriptlet userName = "John"; let userAge = 25;
In this code, userName is a box holding the text "John", and userAge is a box holding the number 25.
Variables help us:
- Store information we need later.
- Make our code reusable.
- Change values as our program runs.
- Keep our code organized and readable.
Now, JavaScript gives us three different ways to create these boxes: var, let, and const. Each one has its own rules and behaviors.
The Three Ways to Declare Variables
JavaScript evolved over time, and so did how we declare variables.
Here are the three keywords:
- var - The original way (introduced in 1995)
- let - The modern way (introduced in ES6/2015)
- const - For values that don't change (also ES6/2015)
Quick example of all three:
typescriptvar oldWay = "I'm from the past"; let modernWay = "I'm the present"; const permanentWay = "I never change";
Each keyword creates a variable, but they behave very differently. Let's explore each one deeply.
Understanding var - The Old Way
What is var?
var was the only way to declare variables in JavaScript for the first 20 years of the language's existence.
Basic syntax:
javascriptvar greeting = "Hello World"; var count = 10; var isActive = true;
You can declare a variable with var, assign it a value, and even change that value later:
javascriptvar score = 100; console.log(score); // Output: 100 score = 200; console.log(score); // Output: 200
So what's the problem? Why did JavaScript introduce let and const if var worked fine? The answer lies in scope and hoisting.
Scope of var Scope determines where your variable can be accessed in your code. Think of it like the area where your variable "lives."
var has function scope, which means:
- Variables declared with var are available throughout the entire function.
- If declared outside any function, they're available globally.
Here's where things get weird:
javascriptfunction testVar() { if (true) { var message = "Hello"; } console.log(message); // Output: "Hello" } testVar();
Notice something strange? We declared message inside the if block, but it's still accessible outside that block. This happens because var ignores block-level scope. For more advanced info on how variables work, check our deep dive on why developers cost their dream jobs.
Real-world problem:
javascriptfor (var i = 0; i < 3; i++) { setTimeout(function() { console.log(i); }, 1000); } // Output: 3, 3, 3 (Not what you expected!)
You might expect this code to print 0, 1, 2. Instead, it prints 3 three times. This happens because var doesn't create a new variable for each loop iteration.
Hoisting with var Hoisting is JavaScript's behavior of moving declarations to the top of their scope before code execution.
With var, the declaration is hoisted, but not the assignment:
javascriptconsole.log(age); // Output: undefined (not an error!) var age = 25; console.log(age); // Output: 25
JavaScript interprets the above code like this:
javascriptvar age; console.log(age); // undefined age = 25; console.log(age); // 25
This can create confusing bugs in your code.
Problems with var Let's summarize the main issues:
- No block scope - Variables leak outside blocks
- Confusing hoisting - Variables can be used before declaration
- Accidental globals - Easy to pollute global scope
- Re-declaration allowed - Can accidentally overwrite variables
javascriptvar name = "John"; var name = "Jane"; // No error! This overwrites the first one console.log(name); // Output: "Jane" These problems led to the creation of let and const.
Understanding let - The Modern Solution
What is let?
let was introduced in ES6 (2015) to solve the problems of var.
Basic syntax:
javascriptjavascriptlet userName = "Sarah"; let userAge = 30;
The key difference? let has block scope.
Block Scope Explained A block is any code wrapped in curly braces {}. This includes:
- if statements
- for loops
- while loops
- Functions
- Any standalone {}
With let, variables only exist within their block:
javascriptfunction testLet() { if (true) { let message = "Hello"; console.log(message); // Output: "Hello" } console.log(message); // Error: message is not defined } testLet();
This is exactly what we want! The variable stays where it belongs.
The loop problem solved:
javascriptfor (let i = 0; i < 3; i++) { setTimeout(function() { console.log(i); }, 1000); } // Output: 0, 1, 2 (Perfect!)
Each iteration creates a new i variable, so the code works as expected.
Hoisting with let let is still hoisted, but with a crucial difference - it enters a "temporal dead zone."
javasriptconsole.log(age); // Error: Cannot access 'age' before initialization let age = 25;
This is better than var because it catches errors early instead of returning undefined.
When to Use let Use let when:
- The variable's value will change
- You need block-level scope
- You're working with loops
- You're reassigning values based on conditions
Example:
javascriptlet score = 0; if (playerWins) { score = score + 10; } if (playerLosses) { score = score - 5; }
Benefits of let
- Block scope - Variables stay where they belong
- No re-declaration - Prevents accidental overwrites
- Clearer errors - Temporal dead zone catches mistakes
- Better loop behavior - Each iteration gets its own variable
javascriptlet name = "John"; let name = "Jane"; // Error: Identifier 'name' has already been declared
Understanding const - The Immutable Choice
What is const?
const stands for "constant" and is used for variables that should never be reassigned.
Basic syntax:
javascriptconst PI = 3.14159; const API_KEY = "abc123xyz"; const MAX_USERS = 100;
The golden rule: You cannot reassign a const variable.
javascriptconst birthYear = 1990; birthYear = 1995; // Error: Assignment to constant variable
When Variables Should Stay Constant Use const for:
- Configuration values
- API endpoints
- Mathematical constants
- Values that shouldn't change during execution
Example:
javascriptconst TAX_RATE = 0.08; const DATABASE_URL = "https://api.example.com"; const ADMIN_EMAIL = "admin@company.com"; function calculateTotal(price) { return price + (price * TAX_RATE); }
const with Objects and Arrays Here's where const gets interesting. While you can't reassign the variable, you can modify the contents of objects and arrays:
javascriptconst person = { name: "John", age: 25 }; // This works! person.age = 26; person.city = "New York"; console.log(person); // { name: "John", age: 26, city: "New York" } // But this doesn't work person = { name: "Jane" }; // Error!
Same with arrays:
javascriptconst colors = ["red", "blue"]; // This works! colors.push("green"); colors[0] = "yellow"; console.log(colors); // ["yellow", "blue", "green"] // But this doesn't work colors = ["pink", "purple"]; // Error!
Why? Because const prevents reassignment of the variable itself, not the modification of its contents. Think of it this way: The box labeled "colors" can't be replaced with a new box, but you can rearrange what's inside the existing box.
Common Mistakes with const
Mistake #1: Forgetting to initialize
javascriptconst age; // Error: Missing initializer in const declaration age = 25;
You must assign a value when declaring const.
Mistake #2: Expecting complete immutability
javascriptconst user = { name: "John" }; user.name = "Jane"; // This works! Many beginners expect an error
If you need true immutability, use Object.freeze():
javascriptconst user = Object.freeze({ name: "John" }); user.name = "Jane"; // Silently fails (throws error in strict mode) console.log(user.name); // Still "John"
Mistake #3: Using const in loops
javascript// This doesn't work for (const i = 0; i < 5; i++) { console.log(i); // Error: Assignment to constant variable } // But this works (each iteration creates a new const) const numbers = [1, 2, 3, 4, 5]; for (const num of numbers) { console.log(num); // Works perfectly! }
Common Mistakes Beginners Make
Mistake #1: Using var in Modern Code
javascript// ❌ Don't do this var userName = "John"; // ✅ Do this instead let userName = "John"; // or const userName = "John";
Why it matters: Modern JavaScript developers expect let and const. Using var makes your code look outdated and can introduce bugs.
Mistake #2: Using let for Everything
javascript// ❌ Inefficient let API_URL = "https://api.example.com"; let MAX_SIZE = 1024; // ✅ Better const API_URL = "https://api.example.com"; const MAX_SIZE = 1024;
Why it matters: Using const signals to other developers (and your future self) that these values shouldn't change. It prevents accidental modifications.
Mistake #3: Not Understanding const with Objects
javascriptconst user = { name: "John" }; // Many beginners think this will error user.age = 25; // This works! // This is what actually errors user = { name: "Jane" }; // Error!
Mistake #4: Declaring Variables Multiple Times
javascript// ❌ This works with var (but it's bad!) var count = 1; var count = 2; // ✅ let and const prevent this mistake let count = 1; let count = 2; // Error! Already declared
Mistake #5: Forgetting Block Scope
javascript// ❌ Common mistake if (true) { let temporary = "test"; } console.log(temporary); // Error: temporary is not defined // ✅ Declare outside if needed elsewhere let temporary; if (true) { temporary = "test"; } console.log(temporary); // Works!
Pro Tips for Writing Better Code
Tip #1: Default to const Start every variable declaration with const. Only use let when you know the value will change.
javascript// ✅ Good practice const userName = "John"; const userEmail = "john@example.com"; let userScore = 0; // This will change
This approach is called "const by default, let when necessary" and is widely used by professional developers.
Tip #2: Use Descriptive Names with const Constants often represent important values, so make their names clear:
javascript// ❌ Unclear const x = 100; const y = 0.08; // ✅ Clear const MAX_USERS = 100; const TAX_RATE = 0.08;
Naming convention: Use UPPERCASE_WITH_UNDERSCORES for true constants (values that never change across the entire application).
Tip #3: Understand the Temporal Dead Zone The Temporal Dead Zone (TDZ) is the period between entering a scope and the variable declaration:
javascript{ // TDZ starts console.log(name); // Error: Cannot access 'name' before initialization let name = "John"; // TDZ ends console.log(name); // Works fine }
This catches bugs early, which is good!
Tip #4: Use let in Loops, const in Iterations
javascript// ✅ Use let for the counter (it changes) for (let i = 0; i < 5; i++) { console.log(i); } // ✅ Use const for each item (it doesn't change within one iteration) const items = ["apple", "banana", "orange"]; for (const item of items) { console.log(item); }
Tip #5: Refactor Old Code Gradually
Found old code with var? Refactor it step by step:
- Replace var with let or const
- Test thoroughly
- Look for scope-related bugs
- Fix any issues that arise
javascript// Before function oldCode() { var total = 0; for (var i = 0; i < 10; i++) { var item = i * 2; total += item; } return total; } // After function modernCode() { let total = 0; for (let i = 0; i < 10; i++) { const item = i * 2; total += item; } return total; }
Best Practices in 2026
The JavaScript community has established clear guidelines for variable declaration:
Modern Standard (Recommended)
- Use const by default - Start here unless you know the value will change.
- Use let when reassignment is needed - Counters, accumulators, conditional values.
- Never use var - It's considered legacy and problematic.
Code Quality Guidelines
✅ Good:
javascriptconst API_ENDPOINT = "https://api.example.com"; const userData = { name: "John", age: 25 }; let currentPage = 1; function updatePage() { currentPage++; fetchData(API_ENDPOINT, currentPage); }
❌ Bad:
javascriptvar API_ENDPOINT = "https://api.example.com"; // Don't use var let userData = { name: "John", age: 25 }; // Should be const const currentPage = 1; // Should be let (it changes)
Team Collaboration Tips
When working on team projects:
- Use ESLint - Configure it to warn about var usage
- Code reviews - Check for proper let/const usage
- Style guide - Document your team's variable declaration standards
- TypeScript - Consider using it for better type safety
Performance Considerations
While the performance difference is minimal, const can offer tiny optimizations:
- JavaScript engines can optimize const better
- Immutability helps with predictability
- Modern bundlers can tree-shake unused const declarations more effectively
Bottom line: Prioritize code readability over micro-optimizations. Use const and let correctly, and performance will follow.
Conclusion
Understanding JavaScript variable declarations is fundamental to writing clean, bug-free code. Let's recap the key points:
- var is the old way with function scope and confusing hoisting behavior. Avoid it in modern code.
- let is perfect for values that change - counters, flags, and variables that get reassigned during execution. It provides block scope and clearer errors.
- const should be your default choice. Use it for values that shouldn't be reassigned, including objects and arrays. It makes your intentions clear and prevents accidental modifications.
The Golden Rule Start with const. Change to let only when you need reassignment. Never use var in new code. This simple approach will make your JavaScript code more predictable, maintainable, and professional. For more career-boosting advice, check out our guide on the JavaScript difference that costs dream jobs.
Your Next Steps
- Review your existing code - Replace var with let or const
- Practice with small projects - Build confidence in choosing the right declaration
- Set up ESLint - Configure it to warn about var usage
- Share this knowledge - Teach others on your team
Remember, every expert developer once struggled with these concepts. With practice, choosing between var, let, and const will become second nature.
Ready to level up your JavaScript skills? Start applying these principles today, and you'll write better code tomorrow.





