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.

CategoryDeclarations
ScopeFunction scope (or global)
HoistingDeclaration is hoisted, assignment is not; the value is undefined before the assignment runs
RedeclareAllowed; the later declaration overwrites
ReassignAllowed
ES versionES1 (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 ChromeChrome EdgeEdge FirefoxFirefox SafariSafari OperaOpera
var v1 v12 v1 v1 v1
Supported by all modern browsers
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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏