JuniorJavaScript

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

  • var is function-scoped, is hoisted (the declaration is moved to the top of the function with the value undefined) and can be declared again.
  • let is block-scoped { }, can't be declared again in the same block, and can't be used before the line that declares it.
  • const is like let but can't be reassigned. Note: an object or array declared with const can still be changed inside.
const doesn't mean immutable
const user = { name: "Alex" };
user.name = "Sam"; // fine
user = {};         // TypeError

A good habit: use const by default, use let only when you really need to reassign, and avoid var in new code.