Variables

let, const, var

What are Variables?

Variables are containers that store values. In JavaScript, you declare a variable using a keyword (var, let, or const), give it a name, and optionally assign an initial value.

Three Declaration Keywords

const (Constant)

Use const by default. It creates a block-scoped variable that cannot be reassigned. This is your first choice for almost all variables.

const name = "Alice";
const age = 25;
const isStudent = true;

// name = "Bob"; // Error: Assignment to constant variable

💡 Important:

const prevents reassignment, not mutation. Objects and arrays can still have their contents modified:

const user = { name: "Alice" };
user.name = "Bob"; // Allowed – modifying the object
// user = {}; // Error – cannot reassign

const numbers = [1, 2, 3];
numbers.push(4); // Allowed – modifying the array
// numbers = []; // Error – cannot reassign

let (Local Variable)

Use let when you need to reassign a value. It is block-scoped, meaning it only exists within the nearest enclosing block (function, loop, if statement).

let count = 0;
count = 1; // Allowed – reassignment is fine
count = 2;

if (true) {
  let localVar = "inside";
  // localVar is only accessible here
}
// console.log(localVar); // Error: localVar is not defined

var (Avoid)

var is the old way to declare variables. It is function-scoped (not block-scoped) and can lead to confusing bugs. Avoid var in modern code.

function example() {
  if (true) {
    var oldWay = "visible outside block";
  }
  console.log(oldWay); // "visible outside block" – leaked outside the block!
}

Scope

Scope determines where a variable is accessible. JavaScript has three types of scope:

🌍 Global Scope

Variables declared outside any function are global (avoid polluting it).

📦 Function Scope

Variables declared inside a function are only accessible within that function.

⛓️ Block Scope

Variables declared with let and const are only accessible within their block (e.g., inside an if, for, or function).

const global = "I'm everywhere";

function example() {
  const functionScoped = "Only here";
  
  for (let i = 0; i < 3; i++) {
    const blockScoped = "Only in the loop";
  }
  // console.log(blockScoped); // Error: not defined
}

Best Practices

  • Use const by default

    It's clear, safe, and prevents accidental reassignment.

  • Use let when you need reassignment

    Be explicit about mutability.

  • Never use var

    It's outdated and confusing.

  • Choose descriptive names

    userName is better than un or x.

  • Declare variables close to use

    Don't declare everything at the top of a function.

Summary Table

Keyword Scope Reassignable Recommended
const Block No Default choice
let Block Yes When needed
var Function Yes Avoid