I. Scoping in programming scoping refers to the accessibility of the variable.
There are mainly 3 types of scoping which are as follows:
1. Global Scope
2. Local Scope
3. Block Scope
1. Global Scope:
When a variable is declared outside of a function, it is in the global scope and
its value is accessible throughout the program. Example:
var myGlobalVar = "This is global!";
function printSomething() {
console.log(myGlobalVar);
}
printSomething(); // Output: This is global!
2. Local (or Function) Scope:
Variables declared within a function are in the local scope, and they cannot be
accessed outside of that function. Example:
function printSomething() {
var myLocalVar = "I'm local!";
console.log(myLocalVar);
}
printSomething(); // Output: I'm local!
// Not allowed
console.log(myLocalVar); // Output: Uncaught ReferenceError: myLocalVar is not
defined
3. Block Scope
Block level scoping, meaning the variable is only accessible within the block it’s
defined i.e in conditional statement block or within loop statement block Example:
if (true) {
let blockScopedVar = "I'm block scoped!";
console.log(blockScopedVar); // Output: I'm block scoped!
}
console.log(blockScopedVar); // Uncaught ReferenceError: blockScopedVar is not
defined
II. Closure(or Lexical Scope) in javascript refers to the variable, which is
defined in the outer function, is accessible to the inner function which is also
defined within the outer function. Example:
function bankRobbery() {
const heroes = ["Spiderman", "Wolverine", "Black Panther", "Batwoman"];
function cryForHelp() {
for (let hero of heroes) {
console.log(`PLEASE HELP US, ${hero.toUpperCase()}`);
}
}
cryForHelp();
}
bankRobbery();