var

Term side of the Card.
Topic: Syntax
Unit title: var
Categories: Syntax, Keyword
Explanation side of the Card

Explanation: The keyword used to declare variables with function scope or global scope, depending on where it's used. Unlike `let` and `const`, which offer block scope, `var` allows redeclaration within the same function or global scope and can lead to unexpected behavior due to its function-wide hoisting.

Browser compatibility:
  • The chrome browser supports this feature starting from version 1.
  • The edge browser supports this feature starting from version 12.
  • The firefox browser supports this feature starting from version 1.
  • The safari browser supports this feature starting from version 1.
Availability: 

Example

Wrongjs
if (isAdmin) {
  var role = 'admin';
}
console.log(role); // 'admin' or undefined
Rightjs
let 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 var counter.
  • A var inside an if block leaking into the whole function.

Key points

  • New code uses const or let instead of var.
  • Refactors from var check 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.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy