Javascriptbeginner6 min read

JavaScript let vs const vs var: Variable Declaration Guide

Comprehensive guide to variable declarations in JavaScript: when to use var, let, or const based on scope and mutability requirements.

#javascript#variables#scope#es6

JavaScript offers three ways to declare variables: var, let, and const. Understanding their differences in scope, hoisting, and mutability is crucial for writing clean, bug-free code.

Scope Differences

  • var: Function-scoped, can be redeclared
  • let: Block-scoped, cannot be redeclared
  • const: Block-scoped, cannot be redeclared or reassigned

Code Example

javascript
// var - function scoped
function testVar() {
  if (true) {
    var x = 10;
  }
  console.log(x); // 10 - accessible outside block
}

// let - block scoped
function testLet() {
  if (true) {
    let y = 20;
  }
  console.log(y); // ReferenceError - not accessible
}

// const - block scoped, immutable
const PI = 3.14159;
PI = 3.14; // TypeError - cannot reassign

Output

10
ReferenceError: y is not defined
TypeError: Assignment to constant variable
💡

Remember This

  • Always prefer const by default, use let when you need reassignment
  • Avoid var in modern JavaScript code
  • const objects can have their properties modified (only the reference is immutable)
📌

Important Rules

  • Use const for variables that should not be reassigned
  • Use let for variables that need to be reassigned
  • Never use var in ES6+ code
⚠️

Common Mistakes

  • Thinking const makes objects completely immutable
  • Using var instead of let in loops
  • Forgetting that let/const are block-scoped
JavaScript let vs const vs var: Complete Variable Declaration Guide | Afzaal Suleman