Syntax:
var variableName = valueOfVar;
Function Scope:Variables declared within a function have function scope and cannot be called outside the function. Variables declared with var are accessible only within this function and its enclosing functions.
Variables declared with the var keyword appear at the top and are initialized with the default value undefine before code execution. Variables declared in global scope outside a 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 go(){ Â Â Â Â console.log(test); } go(); |
12
Example 2: In this example, we will declare multiple variables in a single statement
JavaScript
var test1 = 12, Â Â Â Â test2= 14, Â Â Â Â test3 = 16 function go(){ Â Â Â Â console.log(test1, test2, test3); } go(); |
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; |
undefined
Explanation:The test variable is already displayed at the top before the program execution starts and the variable is initialized with the default value unknown, so you will get the output without any errors.
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); |
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); |
100 12
Explanation: Redeclaring a variable within a different function scope does not generate an error and preserves the variable’s original value.
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); |
Supported Browser:
- Chrome
- Edge
- Firefox
- Opera
- Internet Explorer
- Safari
NOTE: –Â To clear your concept of var, const, and let please go through How to declare variables in different ways in JavaScript?