var (JavaScript)
var is the original keyword for declaring variables in JavaScript. It is function-scoped and hoisted, which is why modern code prefers let and const instead.
JavaScript
Unlike let and const, a var is not limited to the block { } it appears in — it is visible throughout the whole function. var declarations are also hoisted to the top of their scope and initialized as undefined, which can cause surprising bugs.
You will still see var in older code and tutorials, but for new code use const by default and let when you need to reassign.
Syntax
var name = value;Examples
JavaScript
var greeting = "hi";
if (true) {
var greeting = "hello";
}
console.log(greeting);Output:
hello