Posted on

JavaScript – let, const, var

In JavaScript, var, let, and const are three different ways to declare variables, each with distinct behaviors regarding scope, redeclaration, updating, and hoisting. Here’s a detailed explanation of their differences and when to use each:


var

  • Scope:
    var is function-scoped, meaning it is accessible throughout the function in which it is declared. If declared outside any function, it becomes globally scoped.javascriptfunction example() { var x = 10; if (true) { var x = 20; <em>// Same variable, redeclared</em> } console.log(x); <em>// 20</em> }Unlike block-scoping, var ignores block boundaries like {} unless they are part of a function.
  • Redeclaration:
    You can redeclare a var variable within the same scope without errors.javascriptvar a = 5; var a = 10; <em>// No error</em>
  • Updating:
    The value of a var variable can be updated anytime.javascriptvar b = 1; b = 2; <em>// Allowed</em>
  • Hoisting:
    Variables declared with var are hoisted to the top of their scope and initialized with undefined. This means you can use them before their declaration, though their value will be undefined until assigned.javascriptconsole.log(c); <em>// undefined</em> var c = 3;
  • When to Use:
    Use var only when working with older JavaScript code (pre-ES6) or if you specifically need function-scoping. In modern JavaScript, var is generally avoided because its loose scoping rules can lead to bugs, such as unintentional variable overwrites.

let

  • Scope:
    let is block-scoped, meaning it is only accessible within the block (e.g., {}) where it is declared, such as inside loops or if statements.javascriptif (true) { let y = 5; console.log(y); <em>// 5</em> } console.log(y); <em>// ReferenceError: y is not defined</em>
  • Redeclaration:
    You cannot redeclare a let variable within the same scope.javascriptlet z = 10; let z = 20; <em>// SyntaxError: Identifier 'z' has already been declared</em>
  • Updating:
    You can update the value of a let variable after declaration.javascriptlet w = 15; w = 25; <em>// Allowed</em>
  • Hoisting:
    let variables are hoisted to the top of their block but are not initialized. Attempting to use them before declaration results in a ReferenceError (this is known as the “temporal dead zone”).javascriptconsole.log(d); <em>// ReferenceError: Cannot access 'd' before initialization</em> let d = 4;
  • When to Use:
    Use let when you need a variable whose value will change over time, such as a loop counter or a value that will be reassigned.javascriptfor (let i = 0; i < 3; i++) { console.log(i); <em>// 0, 1, 2</em> } console.log(i); <em>// ReferenceError: i is not defined</em>

const

  • Scope:
    Like let, const is block-scoped and is only accessible within the block where it is declared.javascriptif (true) { const k = 100; console.log(k); <em>// 100</em> } console.log(k); <em>// ReferenceError: k is not defined</em>
  • Redeclaration:
    You cannot redeclare a const variable in the same scope.javascriptconst m = 50; const m = 60; <em>// SyntaxError: Identifier 'm' has already been declared</em>
  • Updating:
    You cannot reassign a const variable after its initial assignment. However, if the variable holds an object or array, you can modify its properties or elements (because the reference remains constant, not the content).javascriptconst n = 30; n = 40; <em>// TypeError: Assignment to constant variable</em> const obj = { value: 1 }; obj.value = 2; <em>// Allowed</em> console.log(obj.value); <em>// 2</em> obj = { value: 3 }; <em>// TypeError: Assignment to constant variable</em>
  • Hoisting:
    Like let, const is hoisted but not initialized, so it cannot be accessed before declaration.javascriptconsole.log(e); <em>// ReferenceError: Cannot access 'e' before initialization</em> const e = 5;
  • When to Use:
    Use const for variables that should not be reassigned after initialization, such as constants, configuration values, or references to objects/arrays whose structure might change but whose reference should remain fixed.javascriptconst PI = 3.14159; const settings = { theme: "dark" }; settings.theme = "light"; <em>// Allowed</em>

Key Differences at a Glance

Featurevarletconst
ScopeFunction-scopedBlock-scopedBlock-scoped
RedeclarationAllowedNot allowedNot allowed
UpdatingAllowedAllowedNot allowed (except object/array contents)
HoistingHoisted, initialized with undefinedHoisted, not initializedHoisted, not initialized

When to Use Each

  • var:
    Use sparingly, typically only in legacy code or when you intentionally need function-scoping. Modern JavaScript favors let and const for better predictability.
  • let:
    Use when you need a variable that will be reassigned, such as in loops or when tracking changing state.javascriptlet count = 0; count += 1; <em>// Valid use case</em>
  • const:
    Use by default for variables that won’t be reassigned. This improves code readability and prevents accidental reassignments. It’s especially useful for constants or fixed references.javascriptconst MAX_USERS = 100; const userData = []; userData.push({ name: "Alice" }); <em>// Valid</em>

Best Practices

  • Prefer let and const over var because block-scoping reduces the risk of scope-related bugs.
  • Use const as your default choice to signal intent and prevent unintended reassignments. Switch to let only when reassignment is explicitly required.
  • Avoid var in modern JavaScript unless you have a specific reason tied to its function-scoping behavior.

By understanding these differences and applying these guidelines, you can write cleaner, more maintainable JavaScript code.