var Keyword
Overview
var is the oldest way to declare variables in JavaScript.
Today, you should almost never use var in modern development because its scoping rules are confusing and can lead to hard-to-track bugs. However, you must understand it to read older codebases and pass technical interviews.
Syntax
var is 'function-scoped', meaning it ignores {} blocks like if or for loops. If you re-declare it inside an if block, you accidentally overwrite the variable for the whole function.
function testVar() {
var x = 10;
if (true) {
var x = 20; // This OVERWRITES the x above!
console.log(x); // 20
}
console.log(x); // 20 (Wait, it changed outside the 'if' block!)
}Common Pitfalls
- Using
varin aforloop involving asynchronous code (likesetTimeout). Becausevaris not block-scoped, the loop finishes before the timeout runs, and all timeouts end up printing the final value of the loop counter!
Interview Questions
Because it lacks block scope (ignoring {} in if-statements and loops), allows re-declaration without warning, and gets attached to the global window object, leading to accidental variable overwrites.
Real-World Example
You'll often see var in older legacy enterprise codebases or inside compiled code (when modern JS is transpiled down to ES5 using tools like Babel for older browser support).
// Legacy code you might find at a bank
var userRole = "guest";
if (isAdminLogin) {
var userRole = "admin"; // Dangerously alters the global state
}Check Your Knowledge
Test your understanding of var Keyword with these quick questions.