In JavaScript, the keyword var serves the purpose of declaring a variable. This keyword has been incorporated into the language since its initial iterations. When you utilize var to declare a variable, its scope is determined by the context of the declaration, meaning it is either function-scoped or globally scoped, based on where the variable is defined.
Syntax
The structure of the var keyword in JavaScript is outlined below:
var name = value;
To assign a value, we use the "=" operator.
-
nameis the name of the variable we use. -
valueis what we put in that variable, and it can be whatever you want.
Example
//simple program to print a statement
var Greet = "Hello, Welcome to our tutorial";
console.log(Greet);
Output:
Hello, Welcome to our tutorial
Features of the var keyword
Function Scope
When you declare variables with the keyword var, they are scoped to the function, meaning they can be accessed from any point within that function, including before their actual declaration, owing to a behavior known as hoisting.
Example
function demo(){
var a = 20;
console.log(a);
}
console.log(a); //output: ReferenceError: a is not defined
Global Scope
In JavaScript, declaring a variable outside of any function results in the creation of a global variable, which can be accessed from any part of the program.
Example
var global = "Hello World";
console.log(global);
Output:
Hello World
Re-declaring Variables
Utilizing the var keyword allows for the re-declaration of variables within the same scope without encountering any errors, potentially resulting in unexpected behavior.
Example
var name = "Jhon";
var name = "Rex";
console.log(name);
Output:
Hoisting
When employing the var keyword, the declaration of the variable is elevated to the beginning of its scope; however, the initialization stays in its original position. If you attempt to access a var variable prior to its declaration and initialization, it will yield undefined.
Example
console.log(myVariable); // Output: undefined
var myVariable = 10;
Output:
undefined
No Block Scope
In JavaScript, in contrast to the let and const keywords, the var keyword lacks block scope. This indicates that when a variable is declared using var within a block, it remains accessible beyond that block.
Example
if (true) {
var blockVar = "Learning JavaScript with us is fun.";
}
console.log(blockVar); // Output: Learning JavaScript with us is fun.
Output:
Learning JavaScript with us is fun.
Global Object Property
In the context of a web browser, when we declare a variable using the var keyword at the global level, it effectively becomes a property of the window object. This characteristic can sometimes result in conflicts if not managed with caution.
Performance Considerations
Contemporary JavaScript engines enhance the handling of variables declared with var, while let and const are generally favored for improved clarity and foresight. The usage of var can occasionally result in redundant recalculations, particularly in loops or intricate code structures.
Example
// Inefficient loop
var a = new Array(3).fill(0);
console.time('Execution time')
for (var p = 0; p < a.length; p++) {
console.log(p);
}
console.timeEnd('Execution time')
// Optimized loop
var len = a.length;
console.time('Execution time')
for (var p = 0; p < len; p++) {
console.log(p);
}
console.timeEnd('Execution time')
Output:
0
1
2
Execution time: 2.674ms
0
1
2
Execution time: 0.127ms
Backward Compatibility
The var keyword is recognized in all iterations of JavaScript, which renders it crucial for the upkeep of legacy codebases.
var used with setTimeout
In JavaScript, utilizing var within a loop in conjunction with setTimeout can lead to unforeseen outcomes because of its function-level scope. The variable's value becomes common to every iteration of the loop, resulting in identical outcomes for each invocation of setTimeout.
When to Use
- When you need a variable with function-level scope.
- You are working with older code that doesn't support ES6.
- Typically, you should avoid var, but it can be handy in some cases.
Benefits of the var Keyword in JavaScript
Utilizing the var keyword in JavaScript offers several advantages, including:
- Function scope: In JavaScript, variables declared with
varare available throughout the entire function in which they are defined. - Hoisting: Variables declared using
varare lifted to the beginning of their scope and initialized toundefined, enabling them to be referenced prior to their actual declaration within the code. - No block-scope: The var keyword is function-scoped, which means it is not limited to the block in which it is defined. It can lead to unexpected behaviour when we are working with loops or conditional statements.
- Hoisting Quirks: The var keyword can confuse, as variables are available before their declaration.
- Re-declaration Allowed: The var allows re-declaration, unlike let and const, within the scope, which can overwrite the existing variables unintentionally and lead to difficult-to-debug errors.
- Attached to the Global Object: In JavaScript, when we declare in the global scope, var becomes a property of the global object, which can increase the risk of variable name conflicts and unintended overwrites in large codebases.
Limitations of the var Keyword in JavaScript
Conclusion
In summary, although var continues to be commonly utilized and remains supported, it is advisable to prefer let and const in contemporary programming to mitigate issues such as hoisting and the absence of block scope.