var Statement
Last updated: 2026-09-09
var Statement
var was the only way to declare variables before ES6. It is function-scoped rather than block-scoped, so a variable declared inside if or for is still visible outside the braces. Declarations are hoisted (assignments are not) and redeclaration is allowed. Prefer let and const in new code.
| Category | Declarations |
|---|---|
| Scope | Function scope (or global) |
| Hoisting | Declaration is hoisted, assignment is not; the value is undefined before the assignment runs |
| Redeclare | Allowed; the later declaration overwrites |
| Reassign | Allowed |
| ES version | ES1 (1997) |
📝 Syntax
var name = value;
⚙️ Parameters
| 变量名 | Same rules as let; redeclaring the same name is allowed and the later declaration wins. |
|---|---|
| 初始值 | Optional; when omitted the value is undefined because the declaration is hoisted but the assignment is not. |
Returns:Returns nothing — var is a statement.
Mutates the original:No (returns a new value)
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
undefined
assigned later
undefined
⚠️ Warning A var declared at global scope becomes a property of window (let and const do not), which makes accidental collisions with other scripts easy.
💡 Tip When maintaining legacy code you need not rewrite every var at once: write new code with let/const and refactor gradually to avoid subtle scope regressions.
🌐 Browser support
| Browser | |||||
|---|---|---|---|---|---|
| var | ✓ v1 | ✓ v12 | ✓ v1 | ✓ v1 | ✓ v1 |
| Supported by all modern browsers | |||||
🏷️ Related Statements
💡 Related Cases
More case studies coming soon — check back later.
📚 Related Tutorials
❓ FAQ
QWhat exactly gets hoisted with var?
AOnly the declaration is hoisted, not the assignment. When the scope runs, the variable is registered with the value undefined, so reading it before the assignment yields undefined instead of throwing; the actual value is written when execution reaches that line.
QWhy does using var in a loop break event handlers?
AThe loop shares a single var binding, so every callback captures the same variable. By the time the callbacks run the loop has finished and they all read the last value. Switching to let gives each iteration its own copy — the classic closure fix.
QShould I still use var in new projects?
AAlmost never. let and const give you block scope, no redeclaration, and temporal dead zone protection, which removes the most common var-era bugs. Keep var only when maintaining very old code that is never transpiled.