Free lesson · JavaScript Basic to Advance
var, let, and const
Three Ways to Declare a Variable
JavaScript gives you three keywords for creating variables: var, let, and const. They look interchangeable at first glance. They are not.
var oldStyle = "I've been here since 1995";
let modernMutable = "I can change";
const modernConstant = "I cannot be reassigned";
console.log(oldStyle);
console.log(modernMutable);
console.log(modernConstant);
All three lines work. All three create variables. But the rules around each one are different — and the differences matter enormously in real code. Picking the wrong one creates bugs that hide for months and surprise you at the worst possible moment.
If you take one rule from this Topic, take this: in modern JavaScript, use const by default, use let when you need to reassign, and avoid var entirely. The rest of this Topic explains why.
Why JavaScript Has Three Keywords
Interactive animation: Scope and reassignment are different questions - var is function-scoped, let and const are block-scoped, only const cannot be reassigned.
For its first twenty years, JavaScript had only var. That was the only way to create a variable. It came with quirks — variables were function-scoped instead of block-scoped, declarations got "hoisted" in surprising ways, accidental globals were easy to create. These quirks caused real bugs in real codebases for two decades.
ES6 (2015) added let and const to fix these problems. The committee deliberately chose new keywords instead of changing var's behavior, because billions of lines of existing JavaScript depended on the old behavior. Breaking var would break the internet.
The result: today's JavaScript has three keywords, where two of them (let and const) are the modern way and one (var) exists for historical compatibility. You'll see all three in real codebases — var in older code, let and const in modern code. You need to understand all three to read JavaScript fluently.
When I was learning JavaScript in 2018, most tutorials I followed still used var everywhere. I didn't know let and const existed for the first two months. When I finally learned them and went back to read my own old code, I saw bugs I'd written without realizing — accidental reassignments, scope leaks, variables that did the wrong thing because of var's rules. Don't repeat my mistake. Learn let and const first.
const: The Default Choice
const creates a variable that cannot be reassigned after it's declared.
const platformName = "AlgoInsight";
console.log(platformName);
// platformName = "Something Else"; // ❌ TypeError: Assignment to constant variable
The line that's commented out would throw an error. Once you declare with const, the variable is locked to its initial value. JavaScript refuses to let you change it.
Why is this useful? Because most variables in real code should not change after they're created. A user's ID, a configuration value, an array of items being processed — these are things you set once and use repeatedly. Declaring them with const makes that intent visible. Anyone reading your code knows immediately: "this value won't change later."
There's one nuance you need to know about const: it prevents reassignment of the variable, not modification of the value it holds. If the value is an object or an array, you can still modify the contents:
const user = { name: "Olena", role: "Head of Product" };
user.name = "Olena Marchenko"; // ✅ allowed — modifying a property
user.location = "Redmond"; // ✅ allowed — adding a property
console.log(user);
// user = { name: "Someone Else" }; // ❌ would throw — reassigning the variable
The user variable still points to the same object — you've just changed what's inside that object. const only prevents you from pointing the variable at a different object entirely. This trips up beginners constantly. The rule to remember: const locks the variable, not the contents.
Interactive animation: What const actually freezes - changing and adding properties is legal, reassigning the variable throws a TypeError.
let: When You Need to Reassign
let creates a variable that can be reassigned. Use it when you have a genuine reason to change the value later.
let attempts = 0;
console.log(attempts);
attempts = attempts + 1;
console.log(attempts);
attempts = 5;
console.log(attempts);
This works without errors because let allows reassignment. Common cases for let:
- Counters that increment in a loop
- Values that get updated through conditional logic
- State that changes over the lifetime of a function
In modern JavaScript, you'll find that most of your variables should be const and only a small fraction need to be let. If you find yourself writing let constantly, it's worth asking whether your code is doing too much mutation — usually a sign that you can refactor to fewer reassignments.
var: The Legacy Keyword
var is the original variable keyword from 1995. It still works, and you'll see it in older codebases. But it has three specific behaviors that make it dangerous in modern code:
1. var is function-scoped, not block-scoped. This means a var declared inside an if block or a for loop is visible outside that block — which is rarely what you want. We cover this in detail in Topic 3.3.
2. var is hoisted with a confusing initialization. You can use a var variable before the line that declares it, and JavaScript won't error out — it'll just give you undefined. This is one of JavaScript's most-misunderstood behaviors. Topic 3.4 covers it.
3. var allows re-declaration of the same variable. You can declare the same var name twice in the same scope, and JavaScript silently allows it. This makes typos and accidental shadowing harder to catch.
var count = 1;
var count = 2; // ✅ no error — but probably not what you wanted
console.log(count);
// let countModern = 1;
// let countModern = 2; // ❌ would throw — already declared
The single var redeclaration above produces no warning. With let, the same code would throw an error. That error is a feature — it tells you when you've accidentally declared the same variable twice.
Interactive animation: var, let and const compared row by row - scope, reassignment, redeclaration and reading before the declaration line.
The Decision Framework
graph TD
A[I need to declare a variable] --> B{Will the value<br/>need to change?}
B -->|No| C[Use const]
B -->|Yes| D{Are you in modern<br/>JavaScript code?}
D -->|Yes| E[Use let]
D -->|No| F[You're maintaining old code,<br/>match the existing style]
style C fill:#10b981,color:#fff
style E fill:#7c3aed,color:#fff
This diagram shows the decision flow for choosing between var, let, and const. Start by asking whether the value will need to change. If no, use const. If yes, and you're writing modern JavaScript, use let. If you're maintaining older code that uses var throughout, match the existing style for consistency — but in any new code you write, default to const and let.
The rule is simple enough to memorize: const first, let if needed, never var in new code. The first month I followed this rule, I noticed my code had fewer bugs. Not because the rule fixed anything by magic, but because being forced to think "will this change later?" made me write more deliberate code.
Common Pitfalls
Warning: Three traps with variable declarations.
Forgetting that
constdoesn't make objects immutable.const obj = {a: 1}; obj.a = 2;works fine.constonly locks the variable binding, not the value. If you actually need an unchangeable object, useObject.freeze()(covered in Module 7).Using
varbecause you saw it in a tutorial. A lot of free tutorials online still usevaras their default. Anything published before 2016 will look this way. Don't copy this style into new code. The fact that something works doesn't mean it's the right choice.Declaring without any keyword at all. If you write
name = "Olena"withoutvar,let, orconst, JavaScript creates a global variable. This is almost always a bug. In strict mode (which modern code uses by default), this throws an error instead of silently creating a global. We cover strict mode in Module 10.
Why This Matters in Interviews
Interview: "What's the difference between
var,let, andconst?" is one of the top five JavaScript interview questions. The expected answer covers three points:
- Scope:
varis function-scoped;letandconstare block-scoped (covered deeper in Topic 3.3)- Reassignment:
varandletallow reassignment;constdoes not (butconstdoesn't make objects immutable)- Hoisting:
varis hoisted and initialized toundefined;letandconstare hoisted but not initialized — accessing them before declaration throws a ReferenceError (the "Temporal Dead Zone," covered in Topic 3.5)A candidate who can list all three points has signaled deep familiarity. A candidate who only mentions reassignment has signaled surface-level knowledge.
Topic 3.6 — Interview Lens: Variables, Scope, and Hoisting — covers the full interview-prep treatment of these questions, including the output-prediction puzzles interviewers use.
Try It
Exercise: For each scenario, decide whether to use
var,let, orconst:
- A user's ID that you'll use throughout a function
- A counter that increments inside a loop
- A configuration object whose properties you'll add to later
- The result of a calculation that won't change after it's set
- A boolean flag that flips between true and false based on user actions
- An array that you'll push items into throughout a function
Then write a one-line declaration for each. Compare your answers to your teammates' if you have any — the patterns are clearer once you see the same scenarios solved different ways.