var
Declares a function-scoped (or globally-scoped) variable, optionally initializing it.
Syntax
var name;
var name = value;
var name1 = value1, name2 = value2;
Returns
undefined — `var` is a statement and does not produce a value.
Examples
var count = 1;
count = 2;
console.log(count);
Output
2
// var is hoisted and initialized to undefined
console.log(x);
var x = 5;
console.log(x);
Output
undefined
5
// var is NOT block-scoped
if (true) {
var leaked = "visible";
}
console.log(leaked);
Output
visible
Notes
- `var` declarations are hoisted to the top of the enclosing function
and initialized to `undefined`.
- `var` is function-scoped, not block-scoped. Prefer `let` and `const`
in modern code.
- A top-level `var` in a script creates a property on the global object.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 1.0 |
| firefox | 1.0 |
| safari | 1.0 |
| edge | 12 |
| node | 0.10 |