Skip to main content
TOPIC 2 OF 9 · 2 MIN READ

let, var, and const (Difference in Scopes)

In JavaScript, variable declarations are handled using let, var, and const. Each has its own scope rules and use cases, influencing how variables are managed in the code.

Key concepts

var

Function-scoped, can be redeclared, and prone to hoisting issues.

let

Block-scoped, introduced in ES6, safer for modern development.

const

Block-scoped and immutable (cannot be reassigned).

Step by step

Scope:

var is function-scoped:

function example() {
  if (true) {
    var x = 10;
  }
  console.log(x); // 10
}

let and const are block-scoped:

if (true) {
  let x = 10;
  const y = 20;
}
console.log(x, y); // ReferenceError

Redeclaration:

var allows redeclaration; let and const do not:

var x = 1;
var x = 2; // Allowed
let y = 1;
let y = 2; // SyntaxError

Mutability:

const prevents reassignment but does not make objects immutable:

const obj = { name: 'Alice' };
obj.name = 'Bob'; // Allowed
obj = {}; // Error

Examples

var hoisting issue:

console.log(x); // Undefined
var x = 10;

let and const prevent this:

console.log(y); // ReferenceError
let y = 10;

Practise it

Try these without looking back. If you can explain each one out loud, you are ready for this question.

  • Rewrite code using var to use let or const.
  • Explain the output of code snippets that mix scopes.

Summary

Use let and const for predictable scoping and to follow modern best practices. Avoid var in new codebases.

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus