๐ฅ JavaScript Variables Deep Dive โ var, let, and const

When working with JavaScript, understanding var
, let
, and const
is fundamental. They may seem similar at first glance but behave differently under the hood. In this article, we'll explore everything you need to know about them, including scope, hoisting, redeclaration, reinitialization, and best practices.
๐ Scope
var
Function-scoped.
Accessible anywhere within the enclosing function.
function test() {
if (true) {
var x = 10;
}
console.log(x); // 10
}
let and const
Block-scoped.
Accessible only within the block
{}
they are defined in.
function test() {
if (true) {
let y = 20;
const z = 30;
}
console.log(y); // ReferenceError
console.log(z); // ReferenceError
}
โก Hoisting
var
- Hoisted to the top of its scope and initialized as
undefined
.
console.log(a); // undefined
var a = 5;
let and const
Hoisted but not initialized.
Exist in the Temporal Dead Zone (TDZ) until their declaration is evaluated.
console.log(b); // ReferenceError
let b = 10;
console.log(c); // ReferenceError
const c = 15;
๐ Redeclaration
var
- Can be redeclared within the same scope.
var x = 1;
var x = 2; // No error
let and const
- Cannot be redeclared in the same scope.
let y = 1;
// let y = 2; // SyntaxError
const z = 1;
// const z = 2; // SyntaxError
๐ Reinitialization
var and let
- Can be reassigned.
var a = 5;
a = 10;
let b = 15;
b = 20;
const
- Cannot be reassigned after initialization.
const c = 25;
// c = 30; // TypeError
๐ Global object property
When declared in the global scope:
var
creates a property on the globalwindow
object (in browsers).let
andconst
do not.
var a = 1;
let b = 2;
const c = 3;
console.log(window.a); // 1
console.log(window.b); // undefined
console.log(window.c); // undefined
๐ก Best Practices
โ Prefer
const
by default. It prevents accidental reassignment.โ Use
let
when you know the variable will change.โ Avoid
var
in modern code unless needed for legacy support.
๐งพ Summary Table
Feature | var | let | const |
Scope | Function | Block | Block |
Hoisted | Yes (init as undefined) | Yes (TDZ) | Yes (TDZ) |
Redeclare | Yes | No | No |
Reassign | Yes | Yes | No |
Global prop | Yes | No | No |
โ Conclusion
Understanding the subtle but important differences between var
, let
, and const
helps you write safer, clearer, and more modern JavaScript code. Embrace const
and let
, and reserve var
for very specific cases where its function-scoping behavior is required.
Subscribe to my newsletter
Read articles from pushpesh kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
