← All tutorials

GoCareerGo Tutorials

JavaScript Tutorial

Variables to closures, promises, the DOM and OOP — a complete JS reference.

var vs let vs const

Three ways to declare a variable in JavaScript, each with different scope and re-assignment rules.

var is function-scoped and hoisted with an initial value of undefined. let and const (ES6) are block-scoped and live in the 'temporal dead zone' until their line executes.

  • var — function scope, can be redeclared and reassigned
  • let — block scope, can be reassigned but not redeclared
  • const — block scope, cannot be reassigned (but object contents can still change)
  • Prefer const by default, let when reassignment is needed, avoid var in modern code
function demo() {
  if (true) {
    var a = 1;   // function-scoped
    let b = 2;   // block-scoped
    const c = 3; // block-scoped, immutable binding
  }
  console.log(a); // 1
  // console.log(b); // ReferenceError
}
Tip

Mention 'temporal dead zone' by name — it's a common follow-up question after var vs let.