var
Declares a function-scoped variable. This is the older way, replaced today by let and const.
Example
#function checkAccess(points) {
if (points >= 100) {
var status = 'premium'
}
return status
}
console.log(checkAccess(150))
console.log(checkAccess(20))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
#var name
var name = value
var name1 = value1, name2 = value2More examples
#console.log(bonus)
var bonus = 50
console.log(bonus)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)
}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
varin new code.letandconsthave predictable block scope and report an error when a variable is used before its declaration. - When refactoring old code, replace
varwithletcarefully. If the variable was used outside the block where it was declared, move the declaration up. - In a plain script (outside a module),
varat the top level creates a property on thewindowobject.letandconstdon’t do that.
Related entries
#- let vs const vs varconst and let have block scope, while var has function scope. const doesn’t allow reassignment. In new code write const, and let only for values that change.
- letDeclares a block-scoped variable whose value you can change later.
- constDeclares a block-scoped constant. A variable like this can’t be assigned a new value.
- functionDeclares a named function: a block of code with parameters that you can call any number of times and that can return a result.
- setTimeout()Runs a function once, after the given number of milliseconds has passed.
Spotted a mistake or missing an example? Write to us.