JavaScript var Keyword
Subject: JavaScript
The var keyword in JavaScript is used to declare variables. Before ES6 introduced let and const, var was the only way to declare variables. Although still valid, it's now considered outdated due to its function scope and hoisting behavior, which can lead to bugs.
Syntax
Example: Using var
Key Features of var
1. Function Scope
Variables declared with var are limited to the function, not the block.
⚠️ var is not block-scoped — which may lead to unexpected results.
2. Hoisting
var declarations are hoisted to the top of their function or global scope.
Is interpreted as:
Only the declaration is hoisted, not the assignment.
3. Can Be Redeclared and Reassigned
You can freely redeclare and reassign variables declared with var in the same scope.
When to Use var
- In legacy JavaScript codebases
- When function-scoping is explicitly needed
- ❌ Avoid in modern development; prefer
letorconst
Key Takeaways
varis function-scoped, not block-scopedvaris hoisted, which can cause confusion if misused- It allows re-declaration and reassignment in the same scope
- Not recommended in modern JavaScript—use
letandconstinstead - Still important to understand for debugging or maintaining older code