var
Example
if (isAdmin) {
var role = 'admin';
}
console.log(role); // 'admin' or undefinedlet role = 'user';
if (isAdmin) {
role = 'admin';
}
console.log(role);var ignores block boundaries; let keeps the variable where it is declared.
Common mistakes
- Loop callbacks all seeing the final value of a
varcounter. - A
varinside anifblock leaking into the whole function.
Key points
- New code uses
constorletinstead ofvar. - Refactors from
varcheck that no code reads the variable before its line or outside its block.
Interview questions
Is var deprecated?
No. var still works and is not removed, but let and const are preferred for clearer scope.
Can I redeclare a var variable?
Yes. var allows redeclaration in the same scope without an error, which can hide bugs.