Introduction

JavaScript provides three ways to declare variables: var, let, and const. Although they look similar, they behave differently in terms of scope, hoisting, and reassignment. Choosing the right one improves code readability, prevents bugs, and aligns with modern JavaScript best practices.

Scope

Scope means the area in which a variable can be used.

Example:

if (true) {
  var a = 1;
  let b = 2;
  const c = 3;
}

console.log(a); // 1 accessible
console.log(b); // Error (not defined outside block)
console.log(c); // Error (not defined outside block)

👉 In modern JavaScript, let and const are safer because they stay inside the block where you define them.

Hoisting

Hoisting means JavaScript moves variable declarations to the top before running the code.

Example:

console.log(a); // undefined
var a = 10;

console.log(b); // Error (TDZ)
let b = 20;

console.log(c); // Error (TDZ)
const c = 30;

👉 Always declare variables before using them. It avoids confusion and errors.

Reassignment and Mutability

Reassignment means changing the value of a variable after declaring it.

Example:

let x = 5;
x = 10; // allowed

const y = 20;
// y = 25; Error: cannot reassign const

const obj = { name: "Alice" };
obj.name = "Bob"; // allowed, property changed

👉 Use const for values you don’t want to reassign. Use let when you know the value will change.

Redeclaration

Redeclaration means declaring the same variable name again in the same scope.

Example:

var a = 1;
var a = 2; // allowed

let b = 3;
// let b = 4; Error

const c = 5;
// const c = 6; Error

👉 To avoid mistakes, prefer let and const.

When to Use Each

Summary

In JavaScript, var, let, and const are used to declare variables, but they behave differently. var is function-scoped, allows redeclaration, and is hoisted with undefined, which often causes bugs. let and const are block-scoped, safer, and should be used in modern code. Use const by default for variables that don’t change, and let for variables that do. Avoid var unless you are working with old code. This approach keeps your code cleaner, safer, and easier to maintain.