javascript

var - Function Scoped

Explore JavaScript's 'var' keyword, understanding its unique function scope behavior, hoisting, and why modern coding prefers 'let' and 'const' for better variable management.

10 min read 8 sections Tutorial
Share

In JavaScript, `var` is an older way to create variables. It works differently from newer keywords like `let` and `const`. Understanding `var` helps you read old code and see why modern JavaScript changed things.

var - Function Scoped

var - Function Scoped

A variable is a named storage for values. In JavaScript, you declare variables using keywords. One of the oldest keywords is var.

var has a special rule called function scope. This means a var variable is only known inside the function where it was created. It behaves differently from let and const, which have "block scope".

What is Function Scope?

When you declare a variable with var inside a function, it is only available to be used within that function. It cannot be seen or used outside of it. This is called function scope.

Function Scope

Variables declared with var are only visible inside the function where they are created. They do not respect 'block' boundaries like if statements.

Hoisting

var declarations are moved to the top of their function (or global) scope during compilation. Only the declaration is hoisted, not the assignment.

Re-declaration

You can declare the same var variable multiple times in the same scope without causing an error. This can lead to unexpected overwriting.

Global Object

When declared outside any function, var variables become properties of the global window object in browsers. This is often undesirable.

What is 'var'?

Getting Started

What is 'var'?

To declare a variable with var, you simply use the var keyword, followed by the variable name, and then an optional value.

This creates a spot in memory that your program can use to store information. You can change the value of a var variable later.

javascript
1// Declare a variable named 'score' and give it a value of 100
2var score = 100;
3console.log(score); // Output: 100
4
5// Change the value of 'score'
6score = 200;
7console.log(score); // Output: 200
8
9// Declare another var variable
10var playerName = "Hero";
11console.log(playerName); // Output: Hero

Why 'var' is often avoided today

var has some confusing behaviors compared to let and const. These behaviors can make code harder to understand and lead to bugs. Modern JavaScript code almost always uses let or const instead of var.

Understanding Function Scope

Understanding Function Scope

Function scope means that a var variable lives only inside the function where it was created. It cannot be accessed from outside that function.

However, var does NOT care about code blocks like if statements or for loops. This is a big difference from let and const, which are limited to those blocks.

javascript
1// Variable declared outside any function has global scope
2var globalMessage = "Hello from global!";
3
4function greet() {
5 // Variable declared inside a function has function scope
6 var functionMessage = "Hello from inside a function!";
7 console.log(globalMessage); // Can access globalMessage
8 console.log(functionMessage); // Can access functionMessage
9
10 if (true) {
11 // var ignores block scope, so this 'var' is still function-scoped
12 var insideIf = "I am inside an if block.";
13 console.log(insideIf);
14 }
15 console.log(insideIf); // ✅ This works! 'insideIf' is still available here.
16}
17
18greet();
19
20console.log(globalMessage); // ✅ Can access globalMessage from outside
21
22// ❌ This will cause an error because functionMessage is function-scoped
23// console.log(functionMessage);
24
25// ❌ This will cause an error because insideIf is function-scoped to 'greet()'
26// console.log(insideIf);
✗ BadProblem with var in blocks
if (true) {
var count = 5;
}
console.log(count); // ✅ No error, prints 5. 'count' leaks out!
✓ GoodSolution with let in blocks
if (true) {
let count = 5;
}
console.log(count); // ❌ ReferenceError. 'count' is contained in the block.

var's Special Behaviors: Hoisting and Redeclaration

var's Special Behaviors: Hoisting and Redeclaration

Two unique features of var are hoisting and re-declaration. Hoisting means JavaScript moves var declarations to the top of their scope before your code runs. Re-declaration means you can declare the same var variable multiple times.

Hoisting with var
console.log(animal); // Output: undefined
var animal = "cat";
console.log(animal); // Output: cat
// JavaScript sees it like this:
// var animal; // declaration is hoisted
// console.log(animal); // animal exists, but is undefined
// animal = "cat";
// console.log(animal);
VS
No hoisting with let/const
// console.log(fruit); // ❌ ReferenceError: Cannot access 'fruit' before initialization
// let fruit = "apple";
// let and const do not hoist the same way.
// They enter a "Temporal Dead Zone" until declared.

Redeclaring 'var' can cause bugs

With var, you can declare the same variable name multiple times in the same scope. This can accidentally overwrite a variable you thought was safe. let and const prevent this by throwing an error if you try to re-declare them.

Why Modern JavaScript Avoids var

Why Modern JavaScript Avoids var

The behaviors of var — especially its function scope and hoisting — can lead to unexpected results. In large programs, these behaviors make it hard to track where a variable is defined or changed.

let and const were introduced to solve these problems. They provide clearer rules and help prevent common coding mistakes.

1

Identify var declarations

Look for any line that uses the var keyword to declare a variable. This is the first step to modernizing old code.

javascript
1var userName = "Alice";
2var userAge = 30;
3var isActive = true;
2

Decide between let and const

If the variable's value will change later, use let. If the value should stay the same, use const. Prefer const whenever possible for safer code.

javascript
1// userName will change
2let userName = "Alice";
3
4// userAge and isActive might not change
5const userAge = 30;
6const isActive = true;
3

Refactor your code

Replace var with let or const throughout your program. Test carefully to make sure everything still works as expected.

javascript
1let userName = "Alice";
2userName = "Bob"; // ✅ Works with let
3
4const userAge = 30;
5// userAge = 31; // ❌ Would cause an error with const

Global object pollution with 'var'

When you declare var outside any function, it automatically becomes a property of the global window object in browsers. This is called global pollution and can cause naming conflicts with other scripts. let and const do not do this, keeping the global scope cleaner.

var vs. let/const: A Quick Comparison

var vs. let/const: A Quick Comparison

Featurevarletconst
ScopeFunction scopeBlock scopeBlock scope
Can Reassign?YesYesNo (value is constant)
Can Redeclare?YesNo (throws error)No (throws error)
HoistingYes (initializes to `undefined`)Yes (but in Temporal Dead Zone)Yes (but in Temporal Dead Zone)
Global ObjectAttaches to `window`Does not attach to `window`Does not attach to `window`

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

What is the scope of a variable declared with var?

Quick Check

What happens if you re-declare a var variable in the same scope?

Quick Check

Which of these is true about var hoisting?

Quick Check

Why is var generally discouraged in modern JavaScript development?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1var keyword — the original way to declare variables in JavaScript, now largely replaced by let and const.
  • 2Function scopevar variables are only accessible within the function they are declared in, ignoring if or for blocks.
  • 3Hoistingvar declarations are moved to the top of their scope, but assignments stay in place; variables are initialized to undefined.
  • 4Re-declaration — you can declare the same var variable multiple times in the same scope without an error, potentially overwriting values.
  • 5Global object pollutionvar declared globally (outside any function) attaches itself to the window object in browsers, which can cause conflicts.
  • 6Avoid in new code — always use let or const for new variable declarations to prevent common pitfalls and improve code clarity.
  • 7Legacy code — understanding var is important for working with older JavaScript projects or reading legacy code examples.
  • 8let vs. varlet has block scope and does not allow re-declaration, making it safer and more predictable.
  • 9const vs. varconst also has block scope, does not allow re-declaration, and its value cannot be reassigned after initial setup.
  • 10Debugging complexity — the loose scoping and hoisting of var can make it harder to debug unexpected variable values or side effects.

let Variables

Learn about the let keyword, its block scope, and how it improves on var for mutable variables.

const Variables

Discover the const keyword, how to declare constant variables, and why it's preferred for values that should not change.

Block Scope

Understand the concept of block scope and how let and const limit variable access to specific code blocks.

Global Scope

Explore global scope in JavaScript and the best practices for managing variables accessible throughout your entire application.

You now understand 'var'!

You have learned about the var keyword, its function scope, hoisting, and why it's generally avoided in modern JavaScript. This knowledge helps you understand older code and appreciate the improvements brought by let and const.

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning