The JavaScript var statement
The var keyword is the original, legacy way to declare a variable. It's function-scoped and hoisted, which causes subtle bugs that the block-scoped let and const fixed. In modern code you should use const and let instead; var is mainly something to recognize in older code.
Overview
var is how variables were declared before 2015, and you'll still meet it in older code, so it's worth understanding even though you shouldn't reach for it in new work. The reasons it fell out of favor are the same reasons let and const exist.
Its scoping is the core problem. var is function-scoped, not block-scoped, so a var declared inside an if or for block leaks out to the whole surrounding function. It's also hoisted and initialized as undefined, meaning you can reference it before its declaration line without an error; you just get undefined, which hides bugs rather than surfacing them. And it can be silently redeclared, overwriting an earlier one.
Those behaviors led to a famous class of loop bugs (every callback sharing one leaked var) that the per-iteration block scope of let solves cleanly. The bottom line: use const by default and let when you must reassign; treat var as legacy.
Syntax
var x = 1; // function-scoped, hoisted
function demo() {
if (true) { var y = 2; }
return y; // 2 - var leaked out of the if block
}
// modern: use const / let instead
const a = 1;
let b = 2;
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
function scopeDemo() {
if (true) {
var leaked = 'I leaked out';
}
return leaked; // accessible - var is function-scoped
}
document.getElementById('out').textContent = scopeDemo();
</script>
Best practices
Frequently asked questions
What is the difference between var, let and const?
Why should I avoid var?
undefined), both of which cause subtle bugs.What does it mean that var is hoisted?
undefined, so referencing it before its line gives undefined instead of an error.Is var still supported?
const and let for safer scoping.