JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
Next
javascript
junior
variables

What is the difference between var, let, and const in JavaScript?

variables
scope
hoisting
es6
fundamentals
Quick Answer

var is function-scoped and can be redeclared, let is block-scoped and can be reassigned, const is block-scoped and cannot be reassigned after initialization.

Detailed Explanation

JavaScript has three ways to declare variables:

var:

  • Function-scoped (or globally scoped if declared outside a function)
  • Can be redeclared and reassigned
  • Hoisted to the top of its scope (initialized as undefined)
  • Can be used before declaration (will be undefined)

let:

  • Block-scoped (limited to the block, statement, or expression where it's used)
  • Cannot be redeclared in the same scope
  • Can be reassigned
  • Hoisted but not initialized (Temporal Dead Zone)

const:

  • Block-scoped like let
  • Must be initialized at declaration
  • Cannot be reassigned (but objects/arrays can be mutated)
  • Hoisted but not initialized (Temporal Dead Zone)

Code Examples

Scope differences
function scopeExample() {
  if (true) {
    var x = 'var';
    let y = 'let';
    const z = 'const';
  }
  console.log(x); // 'var' - accessible (function-scoped)
  console.log(y); // ReferenceError - not accessible (block-scoped)
  console.log(z); // ReferenceError - not accessible (block-scoped)
}

Real-World Applications

Use Cases

Configuration Constants

Using const for API URLs, environment settings, and configuration values that should never change during runtime

Loop Iterators

Using let in for loops to maintain proper block scope and avoid closure issues with asynchronous callbacks

Module Imports

Using const for imported modules and dependencies to prevent accidental reassignment

Mini Projects

Scope Visualizer

beginner

Build an interactive tool that highlights variable accessibility across different scopes (global, function, block)

Temporal Dead Zone Demo

intermediate

Create an interactive demonstration showing TDZ behavior with let and const declarations

Industry Examples

ESLint

The no-var rule discourages var usage and enforces let/const for proper block scoping

ESLint

The prefer-const rule flags let variables that are never reassigned, encouraging immutability

Airbnb

Their JavaScript Style Guide mandates const by default, using let only when rebinding is needed

Resources

MDN - var

docs

MDN - let

docs

JavaScript.info - Variables

article
Next
What are the primitive data types in JavaScript?