What is the difference between Var, let and const? Old age question.
If you’re starting your JavaScript journey, choosing the right declaration method — var, let, or const — can be confusing. This article breaks it down with examples to make it simpler.
Scope
- var: Has function scope, meaning it can be accessed anywhere within the function where it’s declared.
function testVar() {
if (true) {
var x = 10; // `var` ignores block scope
}
console.log(x); // Output: 10
}- Even though x is declared inside the if block, it can be accessed outside within the same function.
- let and const: Both have block scope, meaning they can only be accessed within the block where they’re declared.
Hoisting
All declarations (var, let, const) are hoisted, but there’s a key difference:
- var is initialized as undefined.
- let and const remain uninitialized, causing a ReferenceError if accessed before their declaration. This period is known as the Temporal Dead Zone (TDZ).
As a task do a search on Temporal Dead Zone.
console.log(a); // Output: undefined
var a = 5;console.log(b); // Error: Cannot access 'b' before initializationGet Nitish Poonia’s stories in your inbox
Join Medium for free to get updates from this writer.
let b = 10;console.log(c); // Error: Cannot access 'c' before initialization
const c = 15;
Reassignment
- var and let: Can be reassigned.
- const: Cannot be reassigned, but the properties of objects declared with const can be modified.
Redeclaration
- var: Can be redeclared in the same scope (not recommended).
- let and const: Cannot be redeclared in the same scope, making the code more predictable.
var x = 10;
var x = 20; // Works finelet y = 30;
let y = 40; // Error: Identifier 'y' has already been declaredconst z = 50;
const z = 60; // Error: Identifier 'z' has already been declared
Takeaway
Use const for values you don’t plan to reassign, let for variables with a limited scope, and avoid var unless absolutely necessary. This ensures cleaner and more maintainable code.





