var
The legacy way to declare a variable.
Available since: ES1
Syntax
var name = valueExamples
A var variable ignores blocks:
if (true) {
var color = 'red';
}
console.log(color);Output:
redThe declaration is hoisted to the top of the function:
console.log(total);
var total = 5;
console.log(total);Output:
undefined
5Notes
A var is scoped to the whole function, not the block, and can be used before its declaration (it is undefined then). This leads to subtle bugs, so modern code uses let and const.
See also
- let — Declares a variable whose value can change.
- const — Declares a variable that cannot be reassigned.
- globalThis — The global object, available the same way in browsers, workers and Node.js.
In the tutorial
- Variables — How to declare variables in JavaScript with let and const, name them and insert them into strings.