CodePark/ questions / Scope & hoisting
START PRACTICINGPRACTICE
Frontend question · JavaScript › Scope & hoisting

What are the differences between var, let and const?

var is function-scoped, while let and const are block-scoped. const also cannot be reassigned.

var:

  • It is visible in the whole function. It ignores blocks like if and for.
  • It is hoisted (registered before the code runs) and starts as undefined.
  • You can declare it again in the same scope without an error.
  • At the top level of a script, it becomes a property of the global object, like window.x.

let and const:

  • They are visible only inside their block { ... }.
  • They are hoisted too, but they stay uninitialized until their declaration line runs. This period is the temporal dead zone (TDZ). Reading them during the TDZ throws a ReferenceError.
  • You cannot declare them again in the same scope.

const only:

  • You cannot reassign it, and you must give it a value when you declare it.
  • It does not make the value immutable. You can still change a const object or array, for example list.push(4).

A good default: use const, use let when you need to reassign, and do not use var.

  • var is function-scoped. let and const are block-scoped.
  • Hoisted var starts as undefined. let and const are in the temporal dead zone (TDZ) until their line runs.
  • var can be declared twice, and at the top level it creates a property on the global object.
  • const stops reassignment, but the object or array inside can still change.