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. It will be 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
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
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
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
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.
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
'use strict'; var test = 12; delete(test); console.log(test);
Recent Comments