TechnicalEasy JavaScript

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

Asked for Frontend Developer, Full-Stack Developer, Mobile Developer

Why they ask this: Checks that you understand scope and hoisting, which explain many real bugs in JavaScript code.

Answer

  • var is function-scoped, is hoisted and initialised to undefined, and can be re-declared.
  • let is block-scoped ({ ... }), is hoisted but sits in the temporal dead zone until its declaration runs, and cannot be re-declared in the same scope.
  • const behaves like let but the binding cannot be reassigned. The value itself is not frozen: you can still change an object's properties or push to an array.
js
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)); // 3 3 3
for (let j = 0; j < 3; j++) setTimeout(() => console.log(j)); // 0 1 2

const user = { name: 'Sita' };
user.name = 'Ram'; // allowed
// user = {};      // TypeError: Assignment to constant variable

Rule of thumb: use const by default, let when you must reassign, and avoid var in modern code.

Can you explain this in your own words?

Back to question bank