var

Declares a function-scoped variable. This is the older way, replaced today by let and const.

On this page

Example

#
JavaScript
function checkAccess(points) {
  if (points >= 100) {
    var status = 'premium'
  }
  return status
}

console.log(checkAccess(150))
console.log(checkAccess(20))
Console
premium
undefined

Definition and usage

#

var is the oldest way to declare variables in JavaScript. You’ll find it in older tutorials, libraries, and code written before 2015, so it’s worth understanding how it works even if you never use it yourself.

A variable declared with var is scoped to the whole function, not to a block. Declared inside an if or a loop, it’s still visible outside them too. On top of that, the declaration is “hoisted” to the top of the function: the variable already exists from the first line and holds undefined until the program reaches the assignment.

You can declare the same name with var multiple times without any error. Combined with function scope, that makes it easy to accidentally overwrite a value, which is why new code should use let and const.

Syntax

#
Syntax
var name
var name = value
var name1 = value1, name2 = value2

More examples

#
Hoisting: the variable exists before the declaration
JavaScript
console.log(bonus)
var bonus = 50
console.log(bonus)
Console
undefined
50
Pitfall: var in a loop with a delay
JavaScript
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log('var:', i), 0)
}

for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log('let:', j), 0)
}
Console
var: 3
var: 3
var: 3
let: 0
let: 1
let: 2

All the functions from the first loop see the same variable i, which is 3 once the loop finishes. let creates a new variable for every turn.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Don’t use var in new code. let and const have predictable block scope and report an error when a variable is used before its declaration.
  • When refactoring old code, replace var with let carefully. If the variable was used outside the block where it was declared, move the declaration up.
  • In a plain script (outside a module), var at the top level creates a property on the window object. let and const don’t do that.

Related entries

#

Spotted a mistake or missing an example? Write to us.