Favorites

JavaScript var Declaration

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
var
JavaScript DeclarationsThis declaration is supported by all modern browsers.
Updated 28th November 2026

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

console.log(hoisted);
var hoisted = 'now set';

if (true) { var leaks = 'visible outside the block'; }
console.log(leaks);

for (var i = 0; i < 3; i++) setTimeout(() => console.log('var i:', i));

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.

This declaration is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee