Sitemap
Nitish Poonia

Nitish Poonia

React Native Developer and part time youtuber

What is the difference between Var, let and const? Old age question.

2 min readJan 15, 2025

--

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;

Get Nitish Poonia’s stories in your inbox

Join Medium for free to get updates from this writer.

console.log(b); // Error: Cannot access 'b' before initialization
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 fine
let y = 30;
let y = 40; // Error: Identifier 'y' has already been declared
const 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.

--

--

Nitish Poonia
Nitish Poonia

React Native Developer and part time youtuber