AceDevHub
Beginner JavaScript Interview QuestionsBeginnerComparison

JavaScript · Question 5

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

Direct answer

var is function-scoped and can be redeclared; let and const are block-scoped, and const additionally prevents reassignment of the binding.

The important differences are scope, redeclaration, reassignment, and behavior before initialization.

  • var: function-scoped (or global at top level in classic scripts), can be redeclared, can be reassigned, and is initialized to undefined during environment setup.
  • let: block-scoped, cannot be redeclared in the same scope, can be reassigned, and cannot be accessed during its temporal dead zone.
  • const: block-scoped, must be initialized, cannot be reassigned, and also has a temporal dead zone.

A const object can still have its properties changed. const user = {name: 'A'}; user.name = 'B'; is valid because the binding still points to the same object.