Understanding var, let, and const in JavaScript
Unlike most programming languages, javascript has three ways of defining variables: var, let, and const. These are used to declare variables, but each works differently. Let’s break it down with simple examples so you can use them confidently.
1. var: The Old Way
var was how variables were declared in JavaScript for many years. While it's still around, it has some quirks that make it less popular today.
Key Features of var:
- Function-scoped: It’s limited to the function it’s declared in, not just a block like
iforfor. - Re-declaration allowed: You can re-declare the same variable in the same scope.
- Awkward behavior: You can use a
varvariable before declaring it.
Example:
var x = 10;
if (true) {
var x = 20; // Same variable as above
console.log(x); // Output: 20
}
console.log(x); // Output: 20
2. let: The Modern Choice
Introduced in ES6 (2015), let is now the preferred way to declare variables, especially when the value needs to change.
Key Features of let:
- Block-scoped: It’s only available within the
{}block it’s defined in. - No re-declaration in the same scope: You can’t declare the same variable twice in the same scope.
- Different behavior unlike
var: You must declare aletvariable before using it.
Get Justin Ezema’s stories in your inbox
Join Medium for free to get updates from this writer.
Example:
let x = 10;
if (true) {
let x = 20; // Different variable than the one above
console.log(x); // Output: 20
}
console.log(x); // Output: 103. const: For Constants
const is also part of ES6 and is used for values that shouldn’t change after they’re assigned.
Key Features of const:
- Block-scoped: Like
let, it’s only available within the block it’s defined in. - Immutable/permanent assignments : You can’t reassign a
constvariable, but if it’s an object or array, you can still modify the contents. - Requires initialization: You must assign a value when declaring it.
Example:
const pi = 3.14159;
console.log(pi); // Output: 3.14159
// pi = 3.14; // Error: Assignment to constant variable
const colors = ["red", "green"];
colors.push("blue"); // You can modify arrays or objects
console.log(colors); // Output: ["red", "green", "blue"]When to Use What?
- Use
constfor values that won’t change (likepior configuration values). - Use
letfor variables whose values might change (like counters or loop variables). - Avoid
var, unless you’re maintaining older code (or like awkward behaviors 😉).
Conclusion
Understanding var, let, and const is a big step in writing better JavaScript code. Start using let and const (and avoid var) in your projects to make your code more predictable and easier to debug.






