Home JavaScript JavaScript var

JavaScript var

Beginner ⏱ 7 min read Updated: Aug 2026
  • var is the original keyword used to declare variables in JavaScript
  • Variables declared with var are function-scoped, not block-scoped
  • A var variable can be redeclared and updated freely
  • var declarations are hoisted to the top of their function
  • Modern JavaScript generally prefers let and const over var
  • var can still be found in a lot of older, existing code

What Is var in JavaScript?

The var keyword was the only way to declare a variable before let and const were introduced. It creates a variable that can be reassigned as many times as needed, which makes it flexible but also, at times, a little unpredictable for beginners.

Important: var ignores block boundaries like if statements and loops; it only respects function boundaries.

Basic Example of var

Example

<script>
var score = 10;
var score = 20;
console.log(score);
</script>
            
Result
20

Notice that var score was declared twice with no error. This kind of redeclaration is allowed with var, but it is one of the reasons var can cause confusing bugs in larger programs.

Function Scope, Not Block Scope

A variable declared with var inside an if block or a for loop is not limited to that block. It "leaks" out and becomes available anywhere inside the surrounding function, which often surprises beginners who expect it to disappear once the block ends. This behaviour is different from let and const, which respect block boundaries properly.

Key Characteristics of var

Function-Scoped

Visible throughout the entire function it was declared in, not just its block.

Redeclarable

The same variable name can be declared again without an error.

Hoisted

The declaration is moved to the top of its scope during execution, though its value is not.

Global Property

A global var becomes a property of the window object in browsers.

Understanding Hoisting with var

JavaScript processes var declarations before running the rest of the code, which means you can technically reference a var variable before the line where it is declared, and it will simply be undefined rather than throw an error. This behaviour, called hoisting, can hide mistakes that would otherwise be easy to spot, which is another reason developers now lean toward let and const.

Why var Is Less Common Today

Since 2015, JavaScript has offered let and const, which fix many of the quirks of var by respecting block scope and preventing accidental redeclaration. Most style guides and modern codebases now recommend using let and const instead, and reserve var mainly for reading or maintaining older code. Still, understanding var is important, because plenty of existing JavaScript on the web continues to use it.