Open In App

JavaScript Var Statement

Last Updated : 10 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The var keyword is used to declare variables in JavaScript. It has been part of the language since its inception. When a variable is declared using var, it is function-scoped or globally-scoped, depending on where it is declared.

Syntax

var variable = value;

It declares a variable using var, assigns it a value, and allows it to be re-declared or updated within its scope.

Features of var Keyword

1. Function Scope

Variables declared using var are function-scoped. This means they are accessible anywhere within the function they are declared, even before their declaration due to hoisting.

JavaScript
function testVar() {
    var x = 10;
    console.log(x); // Output: 10
}

console.log(x); // Error: x is not defined

Output

Screenshot-2025-02-10-135916
Var Function Scope
  • The variable x is declared using var inside the testVar function, so it is only accessible within that function. Trying to access x outside the function results in an error.
  • Since x is not defined globally, calling console.log(x); outside testVar causes a ReferenceError, as x does not exist in the global scope.

2. Global Scope

If var is used outside of any function, it creates a global variable, accessible anywhere in the script.

JavaScript
var globalVar = "I am global";
console.log(globalVar); // Output: I am global

Output
I am global

Here, globalVar is accessible globally and can be used anywhere in the script.

3. Re-declaration of Variables

var allows you to re-declare variables within the same scope without throwing any errors, which can lead to unintended behavior.

JavaScript
var a = 5;
var a = 10;
console.log(a); // Output: 10

Output
10
  • The var keyword allows the same variable (a) to be declared multiple times in the same scope without errors.
  • The second declaration var a = 10; overwrites the previous value (5), so console.log(a); outputs 10.

4. Hoisting

Variables declared with var are hoisted to the top of their scope, meaning the declaration part is moved to the top, but not the initialization. This can result in undefined behavior if not understood properly.

JavaScript
console.log(hoistedVar); // Output: undefined
var hoistedVar = "Hoisted!";

Output
undefined

Since the declaration is hoisted but not initialized, it prints undefined before the variable is assigned its value.

5. No Block Scope

Unlike let and const, var does not have block scope. Variables declared with var inside a block (like an if or for loop) are accessible outside that block.

JavaScript
if (true) {
    var blockVar = "I am not block scoped";
}
console.log(blockVar); // Output: I am not block scoped

Output
I am not block scoped

Here, blockVar is accessible outside the if block because var is function-scoped, not block-scoped.

6. Global Object Property

In browsers, variables declared with var in the global scope become properties of the window object.

JavaScript
var globalVar = "Global";
console.log(module.exports.globalVar); // Output: Global
Screenshot-2025-02-10-140851
Global Object Property

This behavior can lead to conflicts if not carefully managed, as globalVar is both directly accessible and part of the global window object.

7. Performance Considerations

Though modern JavaScript engines optimize the use of var, let and const are typically preferred for better predictability and readability. Using var can sometimes lead to unnecessary recalculations in loops or complex code.

JavaScript
// Inefficient loop 

var a = new Array(10).fill(0);
console.time('Execution time')
for (var i = 0; i < a.length; i++) {
    console.log(i)
}
console.timeEnd('Execution time')



// Optimized loop 

var len = a.length;
console.time('Execution time')
for (var i = 0; i < len; i++) {
    console.log(i)
}
console.timeEnd('Execution time')

Output
0
1
2
3
4
5
6
7
8
9
Execution time: 3.378ms
0
1
2
3
4
5
6
7
8
9
Execution time: 0.918ms

In this example, storing arr.length in a variable improves performance, particularly for large arrays, by avoiding recalculation in each iteration.

8. Backward Compatibility

The var keyword is fully supported in all versions of JavaScript, making it essential for maintaining older codebases.

JavaScript
var oldBrowserSupport = "Works everywhere!";
console.log(oldBrowserSupport); // Output: Works everywhere!

Output
Works everywhere!

When var is used at the global level, oldBrowserSupport becomes a property of the window object in browsers, making it accessible globally.

9. var used with setTimeout()

When used inside loops with setTimeout(), var can cause unexpected behavior due to its function scope. The value of the variable will be shared across all iterations of the loop, leading to the same result for each setTimeout() call.

JavaScript
for(var i=0;i<=4;i++)
{
    setTimeout(()=>{
        console.log(i)
    },1000)
}

Output

Screenshot-2025-02-10-141849
var used with setTimeout()

Here, i will always be 5 because the setTimeout callbacks share the same reference to i, which ends up being 5 after the loop ends.

Interesting facts about var

  • Closure Issue in Loops: When var is used inside a loop with setTimeout(), all scheduled functions share the same reference to the loop variable. This often leads to unexpected results where the final value of the loop variable is printed multiple times instead of incremental values.
  • Lack of Block Scope: var does not have block scope, meaning that variables declared inside a loop remain accessible outside of it. When used with setTimeout(), this can cause unexpected behavior since all timeout callbacks reference the same variable.
  • Hoisting Behavior: Variables declared with var are hoisted to the top of their function or global scope. However, their initialization remains in place, which can cause undefined values when used inside setTimeout() before being assigned a value.
  • Global Object Attachment: When var is declared in the global scope, it becomes a property of the window object in browsers. This means that any setTimeout() function referencing a var global variable can access it through window.
  • Fixes for var Issues: The unintended behavior of var with setTimeout() can be corrected by using let (which creates a new block-scoped variable for each iteration) or by using an IIFE (Immediately Invoked Function Expression) to create a new function scope for each timeout callback.

Drawbacks of using var

  • No Block Scope: var is function-scoped, meaning it is not limited to the block in which it is defined. This can lead to unexpected behavior when working with loops or conditional statements, as the variable remains accessible outside its intended block.
  • Hoisting Can Cause Unexpected Issues: Variables declared with var are hoisted to the top of their scope but are initialized as undefined. This means they can be referenced before their actual declaration, which can lead to confusion and potential bugs.
  • Re-declaration Allowed: Unlike let and const, var allows re-declaration within the same scope, which can overwrite existing variables unintentionally and lead to difficult-to-debug errors.
  • Attached to the Global Object: When declared in the global scope, var becomes a property of the global object (window in browsers, global in Node.js). This increases the risk of variable name conflicts and unintended overwrites in large codebases.
  • Issues with Asynchronous Code: When used inside loops with functions like setTimeout(), var creates unexpected behavior due to its function scope. Since all iterations share the same variable reference, asynchronous callbacks often use the final value of the variable instead of the expected incremental values.

Conclusion

While var is still valid and widely supported, it’s generally better to use let and const in modern code to avoid pitfalls like hoisting and lack of block scope. However, a thorough understanding of var is indispensable for debugging and maintaining legacy JavaScript projects.


Next Article

Similar Reads