JavaScript var Declaration
The var declaration creates a function-scoped variable. It is the original way to declare variables, now mostly replaced by let and const.
Description
The var statement declares a variable that is scoped to the whole function (or the global scope), not to the block it's written in. Declarations are hoisted: the variable exists from the start of the function with the value undefined, so using it before the line that assigns it gives undefined rather than an error. It can be declared twice without complaint, and at the top level it becomes a property of window.
These behaviors cause subtle bugs, especially in loops with callbacks, which is why modern code uses let and const instead.
Variables declared with var inside a function are local to that function, so the main difference from let is the lack of block scope. In old code you'll often see an immediately invoked function expression, (function () { var x = 1; })(), used to create a private scope; modules and block-scoped declarations make that unnecessary now. You'll still meet var in older tutorials and libraries, so it's worth understanding how hoisting works even if you don't use it.
Syntax
var name;
var name = value;Example
Browser Support
The following information will show you the current browser support for the var declaration. Hover over a browser icon to see the version that first introduced support for this declaration.
Desktop





Tablets & Mobile





