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
varis function-scoped, is hoisted and initialised toundefined, and can be re-declared.letis block-scoped ({ ... }), is hoisted but sits in the temporal dead zone until its declaration runs, and cannot be re-declared in the same scope.constbehaves likeletbut 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 variableRule 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?