JAVASCRIPT

JavaScript var: Syntax, Usage, and Examples

var is the original keyword for declaring variables in JavaScript. You still see it in older code, but modern JavaScript usually prefers let and const because they behave in more predictable ways.

How to Use var

You declare a variable with var, then assign it a value.

Basic syntax

var username ="Mina";
console.log(username);

You can also declare a variable first and assign later:

var score;
score =12;
console.log(score);

var is function-scoped

One of the biggest things to know about var is scope. Scope describes where a variable exists and where you can access it.

var is function-scoped, meaning it only respects function boundaries, not block boundaries like if or for.

functionshowMessage() {
if (true) {
var message ="Hello!";
  }

// This still works because var ignores the if block
console.log(message);
}

showMessage();

That might look convenient, but it often causes confusion because the variable “escapes” the block.

var ignores block scope

A variable declared with var inside an if statement still exists outside that if.

if (true) {
var mood ="happy";
}

console.log(mood);// "happy"

With let or const, this would throw an error because they are block-scoped.

var can be re-declared

var allows you to declare the same variable name more than once in the same scope.

var city ="Vienna";
var city ="Podgorica";

console.log(city);// "Podgorica"

This can hide mistakes. You might re-declare something without realizing it, and the last declaration wins.

var is hoisted

Hoisting means JavaScript moves declarations to the top of their scope before running your code.

With var, the declaration is hoisted, but the value assignment is not. So the variable exists early, but starts as undefined.

console.log(status);// undefined
var status ="active";
console.log(status);// "active"

JavaScript treats it like this behind the scenes:

var status;
console.log(status);// undefined
status ="active";
console.log(status);// "active"

This behavior surprises people because the code runs without throwing an error, even though it looks like you're using the variable before declaring it.

When to Use var

In 2026, var is mostly something you learn to understand older code, not something you reach for in new projects.

1) When you maintain legacy JavaScript code

Many older tutorials, apps, and scripts still use var. If you work on a project that started years ago, you’ll see it everywhere.

Knowing how var behaves makes debugging much easier, especially when variables show up in strange places.

2) When reading old tutorials or interview questions

Some interview questions use var because its scope and hoisting rules create tricky situations. Understanding those rules helps you explain behavior clearly.

3) When you need function scope on purpose

This is rare, but sometimes someone wants a variable to live across an entire function without caring about blocks inside it.

functionbuildGreeting(name) {
if (!name) {
var fallback ="friend";
    name = fallback;
  }

return`Hello, ${name}!`;
}

Modern JavaScript can still do this with let, but var has historically been used that way.

4) When you work with very old environments

Most modern browsers support let and const, but if you ever run JavaScript in an older environment that doesn’t, var might be the only option.

This is unusual now, but it still exists in some embedded systems or old internal tools.

Examples of var

Example 1: Using var in a function

This example shows how var stays available inside the entire function, even if the declaration happens inside a block.

functionprintUserRole(isAdmin) {
if (isAdmin) {
var role ="admin";
  }else {
var role ="member";
  }

console.log(`Role: ${role}`);
}

printUserRole(true);
printUserRole(false);

Because var is function-scoped, the role variable exists everywhere inside printUserRole().

Example 2: var in a loop

var inside a loop can create bugs because the loop variable is shared across iterations.

for (var i =1; i <=3; i++) {
console.log("Count:", i);
}

console.log("After loop:", i);// 4

That last line works because var i still exists outside the loop block.

If you expect i to disappear after the loop, var will disappoint you.

Example 3: The classic click-handler problem

This is one of the most famous “why is my code doing that?” examples.

const buttons =document.querySelectorAll(".btn");

for (var i =0; i < buttons.length; i++) {
  buttons[i].addEventListener("click",function () {
console.log("Clicked button index:", i);
  });
}

You might expect the click to print the correct index. Instead, it prints the final value of i after the loop ends.

That happens because every click handler shares the same var i.

A quick fix is switching to let, since let creates a new binding per iteration:

const buttons =document.querySelectorAll(".btn");

for (let i =0; i < buttons.length; i++) {
  buttons[i].addEventListener("click",function () {
console.log("Clicked button index:", i);
  });
}

Example 4: Hoisting confusion in real code

Here’s a simple bug that happens when you assume a variable will throw an error, but var quietly gives undefined.

functionstartGame() {
console.log(playerName);// undefined
var playerName ="Noah";
console.log(playerName);// "Noah"
}

startGame();

A beginner might read that as “print the player name,” but it prints undefined first. That’s hoisting in action.

Learn More About var

var vs let

The most important difference is scope.

  • var is function-scoped
  • let is block-scoped

That difference changes how variables behave inside loops and conditionals.

if (true) {
var a =1;
let b =2;
}

console.log(a);// 1
console.log(b);// ReferenceError

let stays inside the block, var escapes.

let also doesn’t allow re-declaration in the same scope:

let name ="Sara";
// let name = "Amir"; // SyntaxError

With var, re-declaration is allowed, which can hide accidental mistakes.

var vs const

const is block-scoped like let, but it also prevents reassignment.

const language ="JavaScript";
// language = "Python"; // TypeError

var allows reassignment freely:

var language ="JavaScript";
language ="Python";// allowed

A common modern approach is:

  • Use const by default
  • Use let when reassignment is needed
  • Avoid var in new code

The “temporal dead zone” difference

let and const are also hoisted, but you can’t use them before declaration. Doing so throws a ReferenceError.

console.log(score);// ReferenceError
let score =10;

var behaves differently:

console.log(score);// undefined
var score =10;

That’s a big reason many developers prefer let and const. Errors show up earlier, instead of hiding behind undefined.

Should you replace var in old code?

If you’re modernizing a codebase, you can often replace var with let or const, but you should do it carefully.

Some var code relies on function scope and hoisting. Switching it blindly can introduce bugs, especially in large files.

A safer approach looks like this:

  1. Replace var with const for values that never get reassigned.
  2. Replace var with let for values that do get reassigned.
  3. Run the code and tests after each change.

Quick rules for deciding what to use

Here’s a simple guide you can follow when writing new code:

  • Use const for values that shouldn’t be reassigned.
  • Use let for counters, totals, or variables that change.
  • Use var only when working on older code, or when you absolutely need its behavior.

Summary

var is the classic JavaScript variable keyword, but it comes with tricky behavior like function scope, re-declaration, and hoisting to undefined. Learning var helps you understand legacy code and common bugs. For modern code, let and const are easier to reason about, especially inside blocks and loops.