Select Page

JavaScript var – GeeksforGeeks

Sabya_Samadder
Published: January 31, 2023

JavaScript var is a keyword used to declare variables in JavaScript that are function scoped. Before the introduction of ES6 all the keywords in JavaScript were declared with only “var” keyword. The var keyword is also used to declare global-scope variables.

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 with var can only be accessed inside that function and its enclosing function.

The variables declared using the var keyword 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

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 va 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:

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Internet Explorer
  • Safari

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

Source: www.geeksforgeeks.org