JavaScript Scope
The scope of a variable is region of your program in which it is defined. JavaScript will have only to scopes.
Scope- The scope of a variable is region of your program in which it is defined. JavaScript will have only to scopes. the enclosing context values and expressions are associated.
Why scope
Why scope in JavaScript
-
JavaScript is NOT “some other language”
-
Unlike other languages like C, C++ JavaScript doesn’t support block level scope
-
Supports function level scope
There are three types of scope in JavaScript:
-
Block scope
-
Function scope
-
Global scope
Block scope
A block scoped variable means that the variable defined within a block will not be accessible from outside the block. A block can reside inside a function, and a block scoped variable will not be available outside the block even if the block is inside a function.
Example
For (var i = 0; i <=0; i++) {
// block code
}
Variables declared inside a { } block can be accessed from outside the block.
Function Scope
In Function Scope each function creates a new scope.
In Function scope variables defined inside a function are not accessible (visible) from outside the function.
In Function Scope variables declared with var, let and const are quite similar when declared inside a function.
Example
function vehicle() {
var vehicalName = "car"; // Function Scope
}
Global Scope
Variables declared Globally (outside any function) have Global Scope.
Example
var x = 2; // Global scope