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
Example 2: In this example, we will declare multiple variables in a single statement
12 14 16
Example 3: In this example, we will see the hoisting of variables declared using var
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
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.
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
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
- Internet Explorer