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'?
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.
1// Declare a variable named 'score' and give it a value of 1002var score = 100;3console.log(score); // Output: 10045// Change the value of 'score'6score = 200;7console.log(score); // Output: 20089// Declare another var variable10var 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.
1// Variable declared outside any function has global scope2var globalMessage = "Hello from global!";34function greet() {5 // Variable declared inside a function has function scope6 var functionMessage = "Hello from inside a function!";7 console.log(globalMessage); // Can access globalMessage8 console.log(functionMessage); // Can access functionMessage910 if (true) {11 // var ignores block scope, so this 'var' is still function-scoped12 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}1718greet();1920console.log(globalMessage); // ✅ Can access globalMessage from outside2122// ❌ This will cause an error because functionMessage is function-scoped23// console.log(functionMessage);2425// ❌ This will cause an error because insideIf is function-scoped to 'greet()'26// console.log(insideIf);
if (true) {var count = 5;}console.log(count); // ✅ No error, prints 5. 'count' leaks out!
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.
console.log(animal); // Output: undefinedvar 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);
// 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.
console.log(animal); // Output: undefinedvar 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);
// 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.
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.
1var userName = "Alice";2var userAge = 30;3var isActive = true;
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.
1// userName will change2let userName = "Alice";34// userAge and isActive might not change5const userAge = 30;6const isActive = true;
Refactor your code
Replace var with let or const throughout your program. Test carefully to make sure everything still works as expected.
1let userName = "Alice";2userName = "Bob"; // ✅ Works with let34const 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
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function scope | Block scope | Block scope |
| Can Reassign? | Yes | Yes | No (value is constant) |
| Can Redeclare? | Yes | No (throws error) | No (throws error) |
| Hoisting | Yes (initializes to `undefined`) | Yes (but in Temporal Dead Zone) | Yes (but in Temporal Dead Zone) |
| Global Object | Attaches to `window` | Does not attach to `window` | Does not attach to `window` |
Test Your Knowledge
Test Your Knowledge
What is the scope of a variable declared with var?
What happens if you re-declare a var variable in the same scope?
Which of these is true about var hoisting?
Why is var generally discouraged in modern JavaScript development?
Quick Reference
Quick Reference
- 1
varkeyword — the original way to declare variables in JavaScript, now largely replaced byletandconst. - 2Function scope —
varvariables are only accessible within the function they are declared in, ignoringiforforblocks. - 3Hoisting —
vardeclarations are moved to the top of their scope, but assignments stay in place; variables are initialized toundefined. - 4Re-declaration — you can declare the same
varvariable multiple times in the same scope without an error, potentially overwriting values. - 5Global object pollution —
vardeclared globally (outside any function) attaches itself to thewindowobject in browsers, which can cause conflicts. - 6Avoid in new code — always use
letorconstfor new variable declarations to prevent common pitfalls and improve code clarity. - 7Legacy code — understanding
varis important for working with older JavaScript projects or reading legacy code examples. - 8
letvs.var—lethas block scope and does not allow re-declaration, making it safer and more predictable. - 9
constvs.var—constalso 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
varcan 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.