Lexical Scope JavaScript
-
What is a Scope?
- A Scope refers to the current context of your code.
- It can be either locally or globally defined.
- ES6 gives block scope as well.
- Block scope.
- Function scope.
- Global scope.
-
What is a Lexical Scope?
- A variable defined outside a function can be accessible inside of another function defined after a variable declaration, but the opposite is not true.
-
Example 1
// global scope
var username = "Chaitanya";
function local() {
// local scope
console.log(username);
}
local(); // Chaitanya
// global scope
function local() {
// local scope
var username = "Chaitanya";
}
console.log(username); // undefined
local();
- Example 2: Closures Javascript
// global scope
function subscribe() {
// inner scope 2
var name = "Chaitanya";
function displayName() {
// inner scope
alert(name); // Chaitanya, [[Closures Javascript]]
}
displayName();
}
subscribe(); // alert with Chaitanya