JavaScript var Keyword

JavaScript var Keyword

Learn how the var keyword works in JavaScript, its scope rules, real-world examples, and why modern JavaScript prefers let and const.

In JavaScript, var is a keyword used to declare variables. It was the original method for creating variables in JavaScript and has been part of the language since its introduction in the mid-1990s.

Variables declared using var are either function-scoped or globally scoped, depending on where they are defined. Unlike modern keywords such as let and const, var does not follow block-level scoping, which can sometimes lead to unexpected behavior in larger programs.

Another important characteristic of var is hoisting, meaning variable declarations are moved to the top of their scope during execution. While this behavior can be useful in certain cases, it often makes code harder to read and maintain.

Although var is still fully supported by all modern browsers for backward compatibility, it is generally recommended to use let or const in modern JavaScript applications. These newer keywords provide block-level scoping and help developers write more predictable, secure, and maintainable code.

Syntax of var in JavaScript

Declaring a variable using the var keyword follows a straightforward and readable syntax. This approach was traditionally used in JavaScript before the introduction of let and const.

var variableName = value;
    
  • variableName – the name of the variable, used to store and access data throughout your program
  • value – the data assigned to the variable, such as a string, number, boolean, object, or array
  • The = operator assigns the specified value to the variable

If a variable is declared using var without assigning a value, it is automatically initialized with undefined. This behavior is important to understand when working with legacy JavaScript code.

Example 1: Declaring a Variable Using var

The following example shows how to declare a variable using the var keyword and display its value in the browser console. This is a common pattern found in legacy JavaScript code and older applications.

JavaScript Example

// Declare a variable using var
var greetingMessage = "Hello! Welcome to JavaScript.";

// Print the value to the console
console.log(greetingMessage);
            
Try it Yourself »

Why var Is Not Recommended in Modern JavaScript

Although var is still supported by all modern browsers, its behavior can lead to unexpected results. Features such as function-level scoping and hoisting often make code harder to understand, debug, and maintain, especially in large or complex applications.

With the introduction of ES6 (ECMAScript 2015), JavaScript gained safer and more predictable alternatives that are now considered best practice:

  • let – used for variables whose values may change over time, providing block-level scope
  • const – used for variables that should not be reassigned, helping prevent accidental changes

For modern JavaScript development, using let and const results in cleaner, more readable, and more reliable code.

Features of the var Keyword

The var keyword has several distinctive characteristics that set it apart from let and const. Understanding these features is essential, particularly when reading or maintaining older JavaScript codebases.

1. Function Scope

Variables declared using var are function-scoped, meaning they are accessible anywhere within the function in which they are declared. Unlike let and const, var does not respect block scope such as if or for blocks.

Additionally, var declarations are hoisted to the top of their function scope. While the declaration is hoisted, the assignment remains in place, which can sometimes cause confusion if not properly understood.

JavaScript Example

function demo() {
    var a = 20;
    console.log(a);
}

demo();
console.log(a); // ReferenceError
            
Try it Yourself »

2. Global Scope

When a variable is declared using var outside of any function, it is placed in the global scope. This means the variable can be accessed from anywhere in the application, including inside functions and other script files.

In web browsers, globally declared var variables also become properties of the global window object, which increases the risk of naming conflicts in larger projects.

JavaScript Example

// Global variable declared using var
var siteTitle = "JavaScript Learning Portal";

function showTitle() {
    console.log(siteTitle);
}

showTitle();
console.log(window.siteTitle); // Accessible via the global object
        
Try it Yourself »

3. Re-declaring Variables

The var keyword allows a variable to be re-declared within the same scope without producing an error. While this behavior is valid JavaScript, it can easily introduce logical bugs and make code harder to maintain, especially in large or collaborative projects.

In contrast, attempting to re-declare a variable using let or const in the same scope will result in an error, helping developers catch mistakes early.

JavaScript Example

// Variable re-declaration using var
var userRole = "Admin";
var userRole = "Editor";

console.log(userRole); // Output: Editor
        
Try it Yourself »

Hoisting and Block Scope Behavior of var

The var keyword behaves differently from let and const. Two of its most important characteristics are hoisting and the absence of block-level scope. Understanding these behaviors is critical to avoiding unexpected bugs, especially when working with older JavaScript code.

4. Hoisting

In JavaScript, hoisting means that variable declarations made with var are moved to the top of their scope (global or function) before the code is executed. However, only the declaration is hoisted — the assignment stays where it is.

A helpful real-life analogy is to think of hoisting like reserving a name on a list. JavaScript knows the variable exists, but until a value is assigned, it remains undefined.

Because of this behavior, accessing a var variable before its assignment does not throw an error. Instead, it returns undefined, which can hide logical mistakes in your code.

JavaScript Example: Hoisting with var

// Variable declaration is hoisted
console.log(myVariable); // undefined (not an error)

// Variable assignment happens here
var myVariable = 10;

console.log(myVariable); // 10
            
Try it Yourself »

Internally, JavaScript interprets the above code as if the declaration were written at the top of the scope, while the assignment remains in its original position. This behavior is unique to var and does not apply to let or const.

5. No Block Scope

Unlike let and const, variables declared with var do not follow block scope. This means a variable created inside a block (such as an if statement, for loop, or while loop) is still accessible outside of that block.

A real-life analogy would be writing a note meant for a single meeting room, but leaving it on the building’s main notice board. Even though it was intended for a limited space, everyone can still see and modify it.

This behavior often leads to accidental variable leaks, unexpected value changes, and hard-to-track bugs—especially in large applications or when multiple developers are working on the same codebase.

JavaScript Example: No Block Scope with var

// Variable declared inside a block
if (true) {
    var userStatus = "Logged In";
}

// Still accessible outside the block
console.log(userStatus); // Logged In
        
Try it Yourself »

In modern JavaScript, this issue is avoided by using let or const, which limit the variable’s visibility strictly to the block in which it is declared. This makes code safer, more predictable, and easier to maintain.

Advanced Behavior of the var Keyword

In addition to scope and hoisting, the var keyword exhibits several advanced behaviors that can impact application stability, security, and long-term maintainability. These behaviors are particularly important in browser-based JavaScript and legacy codebases.

6. Global Object Property

When a variable is declared using var in the global scope, JavaScript automatically attaches it as a property of the global object. In web browsers, this global object is the window.

A real-life analogy would be placing your personal belongings in a shared public space. Anyone else using the same space can access, modify, or overwrite them—often without realizing it.

This implicit global binding increases the risk of naming collisions, unexpected overwrites, and difficult-to-debug issues, especially when multiple scripts, third-party libraries, or browser extensions are running on the same page.

JavaScript Example: Global Object Binding

// Global variable declared with var
var appVersion = "1.0.0";

// Accessible through the global window object
console.log(window.appVersion); // Output: 1.0.0
            
Try it Yourself »

Modern JavaScript avoids this issue by using let and const, which do not attach variables to the global object when declared in the global scope. This leads to safer, more modular, and more predictable applications.

7. Performance Considerations

Modern JavaScript engines are highly optimized and handle var, let, and const with comparable performance in most real-world scenarios. In practice, performance differences are usually negligible compared to factors such as algorithm choice and code readability.

However, improper use of var—particularly in loops and shared scopes—can introduce subtle bugs and unnecessary re-evaluations. Writing clear and predictable loop logic is often more important than micro-optimizations.

One common best practice is to cache values, such as an array’s length, when they are used repeatedly inside a loop. This improves readability and can provide minor performance benefits in certain situations.

JavaScript Example: Loop Optimization

// Create an array with sample values
var numbers = [10, 20, 30, 40, 50];

// Loop without caching the length
var start1 = Date.now();
for (var i = 0; i < numbers.length; i++) {
    console.log(numbers[i]);
}
var end1 = Date.now();
console.log("Without cache:", (end1 - start1) + " ms");

// Cache the array length before looping
var length = numbers.length;
var start2 = Date.now();
for (var i = 0; i < length; i++) {
    console.log(numbers[i]);
}
var end2 = Date.now();
console.log("With cache:", (end2 - start2) + " ms");
Try it Yourself »

In modern JavaScript development, prioritizing clean logic and using let or const for block-scoped variables generally leads to more maintainable and reliable code than focusing on minor performance optimizations with var.

8. Backward Compatibility

The var keyword is supported by all versions of JavaScript, including very old browsers and environments that predate ES6 (ECMAScript 2015). For this reason, var remains relevant when maintaining, debugging, or gradually modernizing legacy applications.

However, in modern development workflows, backward compatibility is typically handled through tools such as transpilers (for example, Babel) rather than relying on older language features. As a result, let and const are strongly preferred for new code.

Understanding var is still valuable for reading older codebases, integrating third-party scripts, and preparing for technical interviews—but it should rarely be used in modern production code.

9. Using var with setTimeout()

When var is used inside a loop together with setTimeout(), all scheduled callbacks share the same variable reference. This happens because var is function-scoped rather than block-scoped, which often leads to unexpected results.

A simple real-life analogy is setting multiple reminders that all reference the same changing note. By the time the reminders trigger, the note contains only its final value.

JavaScript Example: var with setTimeout

for (var i = 1; i <= 3; i++) {
    setTimeout(function () {
        console.log(i);
    }, 1000);
}

// Output: 4 4 4
        
Try it Yourself »

By the time the setTimeout callbacks execute, the loop has already completed and the variable i holds its final value (4). Since all callbacks reference the same variable, they all log the same result.

This issue is avoided in modern JavaScript by using let, which creates a new block-scoped variable for each loop iteration, or by wrapping the callback in an immediately invoked function expression (IIFE).

When Should You Use var?

  • When maintaining, debugging, or gradually refactoring legacy JavaScript codebases written before ES6
  • When working in environments where function-level scoping is intentionally required and well understood
  • When supporting very old browsers or platforms that do not provide ES6 support and cannot use modern build tools

For all new and modern JavaScript development, let and const are strongly recommended. They offer block-level scoping, reduce the likelihood of bugs, and result in code that is easier to read, maintain, and scale.

Benefits and Limitations of the var Keyword

Although modern JavaScript development primarily relies on let and const, the var keyword still holds relevance—especially in legacy codebases and older browser environments. Understanding both its strengths and weaknesses enables developers to write safer, more maintainable JavaScript.

Benefits of Using var

  • Function-Level Scope: Variables declared with var are scoped to the entire function, making their behavior consistent and predictable within function-based logic. This was the standard scoping model in JavaScript prior to ES6.
  • Hoisting Behavior: Declarations made with var are hoisted to the top of their scope and initialized with undefined. While this can prevent immediate runtime errors, it requires careful understanding to avoid logic bugs.
  • Universal Compatibility: The var keyword is supported in all JavaScript engines, including very old browsers. This makes it essential when maintaining legacy systems or applications that cannot rely on modern JavaScript features.

Limitations of the var Keyword

  • No Block Scope: Variables declared with var are not confined to block-level structures such as loops or conditional statements.
  • Hoisting Can Reduce Code Clarity: Variables appear usable before they are explicitly defined.
  • Allows Re-declaration: Variables can be re-declared in the same scope, increasing bug risk.
  • Pollutes the Global Scope: Global var variables attach to the global object.

For modern JavaScript development, industry best practices strongly recommend using let and const.