- Home
- /
- var vs let vs const
JavaScript Tutorial
IINTRODUCTION
JAVASCRIPT VARIABLES
JAVASCRIPT BASICS
JAVASCRIPT OBJECTS
DOM & BOM
OOPs
- Home
- /
- var vs let vs const
var vs let vs const
In JavaScript, we often need to store values—like numbers, strings, or objects—for later use. To do that, we declare variables. And JavaScript gives us three keywords to do it: var
, let
, and const
.
But what’s the difference? Which one should you use? Let me explain it like I’m walking you through code in a real project.
Why var Is Old School Now
Back in the early days of JavaScript, var
was all we had. It still works today, but it has some quirks that can make your code confusing. For example, variables declared with var
are function-scoped. That means they are accessible anywhere inside the function, even before they’re declared (a behavior called hoisting).
function test() {
console.log(x); // undefined
var x = 10;
}
This can lead to hard-to-find bugs. Because of these issues, developers now mostly use let
and const
instead.
When to Use let
Introduced in ES6, let
fixes most of the issues var
had. Variables declared with let
are block-scoped—they only live within the curly braces {}
they’re declared in.
Here’s an example:
if (true) {
let message = "Hello!";
console.log(message); // Works
}
console.log(message); // ReferenceError: message is not defined
That’s much safer and easier to reason about. If a variable can change (like user input, counters, etc.), use let
.
When to Use const
Also added in ES6, const
is like let
, but with one important rule: you can’t reassign it. Once you set it, it stays that way.
const pi = 3.14;
pi = 3.14159; // ❌error!
This is great for values that should never change, like API keys, fixed configuration values, or constants like pi
.
Note: const
makes the variable binding constant—not necessarily the value. If it holds an object or array, you can still change the internal contents.
const person = { name: "Arshyan" };
person.name = "Hamza"; // ✅ allowed
Summary
Use
let
when the value needs to change.Use
const
when the value should stay the same.Avoid
var
unless you’re maintaining old code.
In modern JavaScript, sticking with let
and const
keeps your code clean, predictable, and easier to debug. And if you’re unsure, start with const
by default—only use let
when you know you’ll need to change the value.