JavaScript var is a key phrase used to declare variables in JavaScript which are perform scoped. Earlier than the introduction of ES6 all of the key phrases in JavaScript had been declared with solely “var” key phrase. The var key phrase can be used to declare global-scope variables.
Syntax:
var variableName = valueOfVar;
Perform Scope: The variables declared inside a perform are perform scoped and can’t be accessed outdoors the perform. The variables declared with var can solely be accessed inside that perform and its enclosing perform.
The variables declared utilizing the var key phrase are hoisted on the high and are initialized earlier than the execution of code with a default worth of undefined. The variables declared within the international scope that’s outdoors any perform can’t be deleted
Instance 1: On this instance, we’ll declare a worldwide variable and entry it anyplace inside this system
Javascript
|
Output:
12
Instance 2: On this instance, we’ll declare a number of variables in a single assertion
Javascript
|
Output:
12 14 16
Instance 3: On this instance, we’ll see the hoisting of variables declared utilizing var
Javascript
|
Output:
undefined
Rationalization: We get the output with none error as a result of the variable check is hoisted on the high even earlier than the execution of this system started and the variable is initialized with a default worth of undefined
Instance 4: On this instance, we’ll redeclare a variable in the identical international block
Javascript
|
Output:
100
Rationalization: We didn’t get any error when redeclaring the variable if we did the identical with the let key phrase an error can be thrown
Instance 5: On this instance, we’ll redeclare the variable in one other scope and see how it’s the authentic variable.
Javascript
|
Output:
100 12
Rationalization: We didn’t get any error whereas redeclaring the variable inside one other perform scope and the unique worth of the variable is preserved.
Instance 6: On this instance, we’ll attempt to delete a worldwide variable declared utilizing va within the ‘use strict’ mode
Javascript
|
Output:
Rationalization: Each time a variable is said utilizing var in international scope it can’t be configured. Therefore it can’t be deleted utilizing the delete key phrase. and an error is thrown
Supported Browser:
- Chrome
- Edge
- Firefox
- Opera
- Web Explorer
- Safari
P.S: To clear your idea of var, const, and let please undergo declare variables in several methods in JavaScript?