Open In App

JavaScript var

Last Updated : 09 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The JavaScript var statement declares variables with function scope or globally. Before ES6, var was the sole keyword for variable declaration, without block scope, unlike let and const.

Syntax:

var variableName = valueOfVar;

Function Scope

The variables declared inside a function are function-scoped and cannot be accessed outside the function.

The variables declared using the var statement are hoisted at the top and are initialized before the execution of code with a default value of undefined. The variables declared in the global scope that is outside any function cannot be deleted

Examples of JavaScript var

Example 1: In this example, we will declare a global variable and access it anywhere inside the program

Javascript
var test = 12
function foo(){
    console.log(test);
}
foo();

Output:

12

Example 2: In this example, we will declare multiple variables in a single statement

Javascript
var test1 = 12,
    test2= 14,
    test3 = 16
function foo(){
    console.log(test1, test2, test3);
}
foo();

Output:

12 14 16

Example 3: In this example, we will see the hoisting of variables declared using var

Javascript
console.log(test);
var test = 12;

Output:

undefined

Explanation: We get the output without any error because the variable test is hoisted at the top even before the execution of the program began and the variable is initialized with a default value of undefined

Example 4: In this example, we will redeclare a variable in the same global block

Javascript
var test = 12;
var test = 100;
console.log(test);

Output:

100

Explanation: We did not get any error when redeclaring the variable if we did the same with the let keyword an error would be thrown

Example 5: In this example, we will redeclare the variable in another scope and see how it is the original variable.

Javascript
var test = 12;
function foo(){
    var test = 100;
    console.log(test);
}
foo();
console.log(test);

Output:

100
12

Explanation: We did not get any error while redeclaring the variable inside another function scope and the original value of the variable is preserved.

Example 6: In this example, we will try to delete a global variable declared using var in the ‘use strict’ mode

Javascript
'use strict';
var test = 12;
delete(test);
console.log(test);

Output:

Explanation: Whenever a variable is declared using var in global scope it cannot be configured. Hence it cannot be deleted using the delete keyword. and an error is thrown

Supported Browser:

P.S: To clear your concept of var, const, and let please go through How to declare variables in different ways in JavaScript?



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads