JavaScript var | Definition, Syntax, Characteristics and Examples
Have you heard of ‘var’ keyword in JavaScript? Well, in this blog, we will understand everything about it, starting from definition, syntax, characteristics and various examples!
In JavaScript, var is a keyword used to declare variables. Variables are fundamental to any programming language, serving as placeholders or containers for values that can change over time. The var keyword was the primary way to declare variables in JavaScript before the introduction of let and const in ES6 (ECMAScript 2015).
Must read Difference Between var and let in JavaScript
Table of Content
Best-suited JavaScript courses for you
Learn JavaScript with these high-rated online courses
JavaScript ‘var’ Definition
The var keyword in JavaScript is used to declare a variable. It’s one of the ways to store data values, and its usage has several characteristics that distinguish it from other variable declaration keywords like let and const.
Syntax of JavaScript ‘var’
The var keyword in JavaScript is used for declaring a variable, potentially initializing it to a value. The syntax is as follows:
1. Declaration
var variableName;
2. Initialization
var variableName = value;
Where,
- variableName: Name of the variable.
- value: Initial value assigned to the variable.
Characteristics of ‘var‘
- Function Scope: Variables declared with var are scoped to the nearest function block. If declared outside of a function, they are globally scoped.
- Hoisting: var declarations are “hoisted” to the top of their scope. This means that the variable can be used before it’s declared, although it will be undefined until its declaration and initialization (if any) are reached in the code.
- Re-Declaration: Variables declared with var can be re-declared within the same scope without causing an error, which can lead to bugs if done accidentally.
- Initialization: If you declare a variable with var without initializing it (i.e., without assigning it a value), it will have the value undefined.
Examples of JavaScript ‘var’
1. Basic Usage
var greeting = "Hello from ShikshaOnline!";console.log(greeting);
Output
Hello from ShikshaOnline!
This is the most straightforward use of var. A variable greeting is declared and assigned a string value. Then, it’s printed to the console. This shows how to declare and initialize a variable with var.
2. Hoisting
function showHoisting() { console.log(message); var message = "Hoisting example from ShikshaOnline"; console.log(message);
showHoisting();
Output
undefined Hoisting example from ShikshaOnline
In this example, var message is declared and initialized after it’s logged to the console. However, due to hoisting, the declaration of message (var message) is moved to the top of the function, but not its initialization. That’s why it outputs undefined first and then the actual message. This behaviour is specific to var and is an essential concept in JavaScript.
3. Re-declaration and Reassignment
var website = "ShikshaOnline";console.log(website);
var website = "LearningHub";console.log(website);
Output
ShikshaOnline LearningHub
This code shows that var allows re-declaration of the same variable within the same scope without causing an error. Here, the variable website is declared and re-declared with var. This is generally considered a drawback as it can lead to bugs due to accidental re-declaration.
4. Function Scope
function showFunctionScope() { if (true) { var topic = "JavaScript"; } console.log(topic);}
showFunctionScope();
Output
JavaScript
Variables declared with var are function-scoped, not block-scoped. This means topic, even though declared inside an if block, is accessible throughout the entire function showFunctionScope. This is unlike let and const, which are block-scoped.
5. Accidental Global Variables
function setGlobalVariable() { accidentalGlobal = "This is a global variable from ShikshaOnline"; }
setGlobalVariable();console.log(accidentalGlobal);
Output
This is a global variable from ShikshaOnline
Here, accidentalGlobal is declared without var, let, or const, making it a global variable. This can lead to unintended consequences, as global variables can be accessed and modified from anywhere in the code, potentially leading to hard-to-track bugs.
6. Using ‘var’ in Loops
for (var i = 0; i < 3; i++) { setTimeout(function() { console.log(`Loop Index (var): ${i} from ShikshaOnline`); }, 1000 * i);}
Output
Loop Index (var): 3 from ShikshaOnline Loop Index (var): 3 from ShikshaOnline Loop Index (var): 3 from ShikshaOnline
This example highlights a common issue when using var in loops, especially with asynchronous code like setTimeout. The variable i is function-scoped to the nearest function (or globally if not in a function), so by the time the setTimeout callbacks execute, the loop has already completed, and i has its final value (3). Therefore, each callback refers to the same i, resulting in all callbacks logging 3.
Thus, understanding how var works is still important for a comprehensive grasp of JavaScript, particularly when dealing with legacy code, but for new code, the current best practice is to use let and const.
Keep learning, keep exploring!
FAQs
What is var in JavaScript?
var is a keyword used to declare a variable in JavaScript. It's been a part of the language since its early versions. When you declare a variable with var, the variable can have a function scope or a global scope if not declared inside a function.
How does var differ from let and const?
var declarations are function-scoped or globally scoped and are hoisted to the top of their scope, meaning they can be referenced before their declaration. let and const, introduced in ES6 (ECMAScript 2015), are block-scoped (limited to the block in which they are declared) and are not hoisted, which makes them safer to use as they reduce the risk of bugs related to scope confusion.
What is variable hoisting in the context of var?
Variable hoisting is a behavior in JavaScript where var variable declarations are moved to the top of their enclosing scope during the compilation phase. This means a variable can be used before it has been declared. However, only the declaration is hoisted, not the initialization.
Can var variables be redeclared?
Yes, in JavaScript, variables declared with var can be redeclared within the same scope without causing an error. This can lead to issues in larger codebases where variable names might be inadvertently reused, leading to unexpected behaviors.
Why is the use of var often discouraged in modern JavaScript?
The use of var is discouraged in modern JavaScript primarily due to its function-scoped behavior and hoisting, which can lead to bugs, especially in large and complex codebases. let and const provide block-scoped alternatives that are generally considered safer and more predictable, leading to clearer and more maintainable code.
Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio