var Keyword in JavaScript

var Keyword in JavaScript

JavaScript provides three keywords for declaring variables: var, let, and const. The var keyword was the original method used before ES6 introduced let and const. While newer code typically favours the latter two, it’s still important to understand how var behaves, particularly in terms of hoisting and scope when working with legacy code or older tutorials.

Table of Contents:

What is var in JavaScript?

The var keyword in javascript is used for declaring variables in JavaScript. It has been there from the time when language came, and this is the only way to declare the variables in JavaScript until ES6 introduced (let and const).

Example:

Javascript

Output:

var keyword in JavaScript

Explanation: In this example, a variable named name is created with the value “Intellipaat.”

Kickstart your Career in Tech With Hands-On Web Development Training
Start Your Web Development Journey Today!
quiz-icon

Key Features of the var Keyword in JavaScript

Here are the following characteristics of the var keyword in JavaScript that are important to know, whether you are a beginner or experienced in JavaScript:

1. Function Scope of var in JavaScript (With Example)

Variables that are declared with the var keyword are function-scoped. This means they are only accessible inside the function in which they are defined.

Example:

Javascript

Output:

Function Scope of var in JavaScript

Explanation: This example clearly explained to you that variables declared using the var keyword are function-scoped. x is declared inside the function. It is not accessible outside of it.

2. Understanding JavaScript Hoisting Using var

One of the most important and confusing aspects of var is Hoisting (accessing value before declaration). When you declare a variable using var, JavaScript moves the declaration to the top of its scope before execution.

Example:

Javascript

Output:

Hoisting in JavaScript Using var keyword

Explanation: In this example, variable a is declared after the first console.log(a) statement. JavaScript hoisted the declaration. Thus, this is the reason why the first console.log() statement doesn’t throw an error but prints undefined.

3. Why var in JavaScript Has No Block Scope?

Unlike let and const, the var keyword doesn’t have block scope. This means that if you declare a variable using the var keyword inside a block ( {} ), it is also accessible outside the block.

Example:

Javascript

Output:

var in JavaScript Has No Block Scope

Explanation: In this example, variable x is declared inside the if-block. It is still accessible outside of it. And this behaviour of JavaScript sometimes produces unexpected bugs in your code.

4. var Allows Redeclaration—How Does it Works in JavaScript?

Unlike let and const, the var keyword allows you to update and redeclare the same variable within the same scope without giving you any error.

Example:

Javascript

Output:

Redeclaration of var in JavaScript

Explanation: The var keyword gives you the flexibility to change its value whenever you want to change it. This flexibility sometimes produces an error in your code.

Code Comparison: var vs let vs const

Feature var let const
Scope if (true) { var x = 1; } console.log(x); // Accessible if (true) { let y = 2; } console.log(y); // Error if (true) { const z = 3; } console.log(z); // Error
Re-declaration var a = 10; var a = 20; // Allowed let b = 10; let b = 20; // Error const c = 10; const c = 20; // Error
Re-assignment var a = 10; a = 20; // Allowed let b = 10; b = 20; // Allowed const c = 10; c = 20; // Error
Hoisting console.log(x); var x = 5; // undefined (hoisted) console.log(y); let y = 5; // ReferenceError console.log(z); const z = 5; // ReferenceError

var vs let vs const—Key Differences in JavaScript Variable Declaration

Difference between the var, let, and const keywords in JavaScript that are used to declare variables in JavaScript.

Attributes var let const
Scope Functional Scope Block Scope Block Scope
Update/Redeclaration Can be updated and redeclared within the same scope Can be updated but not redeclared within the scope Cannot be updated and redeclared within the scope
Declaration without initialization It can be declared without initialization Can be declared without initialization It cannot be declared without initialization
Access without initialization Accessible, because the default value is undefined Inaccessible without initialization Inaccessible without initialization
Hoisting Hoisted and initialized with default value Hoisted but not initialized Hoisted but not initialized

When to Use var in JavaScript: Best Practices and Use Cases

The JavaScript var scope is generally not recommended in modern JavaScript. But you can use it in other cases like

  • If you’re maintaining an older codebase that depends on JavaScript var scope, it may be best to continue using the var keyword.
  • Having an idea of var helps you debug and understand older JavaScript code.
  • In some cases, you may want to intentionally declare a variable in the global scope, and var allows this. But this is not good practice.
  • The var is not block-scoped; thus, it creates some issues when used inside loops. 

Real-world Use Cases of the var Keyword

  1. Legacy Code Maintenance
    When maintaining or debugging older JavaScript applications written before ES6, you’ll often encounter var. Understanding how it works is crucial to safely refactor or extend the code.
  2. Global Variable Declarations in Older Projects
    In early JavaScript applications, var was commonly used to define global variables, especially when multiple scripts interacted on the same page.
  3. Function-Scoped Variables in Classic Libraries
    Libraries like jQuery or older versions of Angular are used var extensively due to their function-scoped behaviour, making it essential to understand when integrating or updating those systems.
  4. Browser Compatibility Requirements
    Some very old browsers that do not fully support let or const may still require the use of var for compatibility in legacy environments.
  5. Understanding Hoisting in Job Interviews or Exams
    Questions related to var and hoisting are common in technical interviews and academic settings, making it important to know theoretical behaviour even if you don’t use it in practice.
  6. Backward-Compatible JavaScript Tools or Polyfills
    When writing scripts intended to be backward-compatible or embedded in environments where modern JavaScript features aren’t guaranteed, var may still be intentionally used.

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

In conclusion, while var is largely considered outdated in modern JavaScript development, it remains essential for understanding legacy code and certain compatibility scenarios. Its unique behaviours, such as function scope, hoisting, and lack of block scope, can introduce bugs if not properly understood. Developers should prefer let and const in contemporary codebases, but a solid grasp of var is still a valuable skill. Knowing when and why it was used helps bridge the gap between older and modern JavaScript practices.

Further, check out the JavaScript Course and get ready to excel in your career with the JavaScript Interview Questions prepared by experts.

These articles explore the foundational principles of web development using HTML, CSS, and JavaScript.

How to affect other elements when one element is hovered in CSS – Explains how :hover and combinators like + or ~ work.

How to remove the space between inline-block elements in HTML – Suggests removing line breaks and comments in HTML code.

How to use before or after pseudo element to an input field in CSS – Provides workaround by wrapping input in a container div.

Extract properties from objects as array in JavaScript – Demonstrates converting object data into iterable arrays.

Comparing arrays in JavaScript – Shows how to compare array content element by element.

Detect click outside element in JavaScript – Demonstrates conditional logic to check click targets.

Sort an array of objects in JavaScript – Covers sorting by numeric and string object properties.

Most efficient method to groupBy on an array of objects – Demonstrates building maps of arrays by key.

Change URL without reloading the page in Next.js – Helps build dynamic, fast front-end apps in Next.js.

Floating point precision in JavaScript – Shows common pitfalls like 0.1 + 0.2 !== 0.3.

Equality comparison in JavaScript – Demonstrates type coercion in loose comparisons.

JavaScript highest integer value – Explains integer limits based on IEEE-754 standard.

var Keyword in JavaScript – FAQs

Q1. What is the purpose of the var keyword in JavaScript?

The var keyword in JavaScript is used to declare variables. These variables are the storage containers which are used to store values.

Q2. Why was var replaced by let and const?

var was replaced because it has issues like function scoping, hoisting, and a lack of block scope, which led to errors in code.

Q3. Does var get hoisted like let and const?

Yes, but with a big difference –  var is initialized as undefined, while let and const remain uninitialized until they are declared.

Q4. Can I use var inside an if statement?

Yes, but the variable will not be block-scoped, meaning it will be accessible outside the if block.

Q5. How to declare a variable in JavaScript?

To declare a variable in JavaScript, you can use the var keyword, which is the traditional method. Modern JavaScript uses let and const to declare variables.

Q6. What is the difference between var and let?

var is function-scoped, while let is block-scoped.

Q7. Can I use var in modern JavaScript?

Yes, but it’s generally discouraged in favour of ‘let’ and ‘const.’

Q8. Does var support block scope?

No, ‘var’ does not support block scope; it is scoped to the nearest function.

Q9. Why is var hoisted?

‘var’ is hoisted because JavaScript moves declarations to the top of their scope during compilation.

Q10. Should I use var in loops?

No, using ‘let’ in loops is preferred for safer and more predictable behaviour.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner