varis a keyword in JavaScript used to declare variables.- It was the only way to declare variables before ES6 (2015) introduced
letandconst.
πΉ Characteristics of var
-
Function Scoped
- A
varvariable is only scoped to the function in which it is declared. - If declared outside any function, it becomes a global variable.
function test() { if (true) { var x = 10; } console.log(x); // β 10 (accessible because var is function-scoped) } test(); - A
-
Hoisting
- Variables declared with
varare hoisted to the top of their scope. - However, they are initialized with
undefined, not their value.
console.log(a); // β undefined (hoisted, but not assigned) var a = 5; - Variables declared with
-
Can be re-declared and updated
- You can declare the same variable multiple times with
var.
var a = 10; var a = 20; // β allowed console.log(a); // 20 - You can declare the same variable multiple times with
-
Global object property (in browsers →
window)- If declared globally, a
varvariable becomes a property of thewindowobject.
var name = "Dev"; console.log(window.name); // "Dev" - If declared globally, a
πΉ Problems with var (Why let and const were introduced)
β Function scope only → not block scoped, which can cause bugs.
β Hoisting confusion → can lead to undefined issues.
β Re-declaration allowed → can accidentally overwrite variables.
πΉ Example Comparison
if (true) {
var a = 5;
let b = 10;
const c = 15;
}
console.log(a); // β
5 (var is function-scoped, so accessible here)
console.log(b); // β ReferenceError
console.log(c); // β ReferenceError
πΉ Summary
β
var → function-scoped, hoisted, re-declarable, added to global object.
β
Introduced in ES1 (old JavaScript).
β
Replaced by let and const in ES6 for better scoping and safety.