JavaScript has two main types of scopes: global scope and local (or function) scope. A scope in JavaScript determines the accessibility and visibility of variables and functions throughout the code.
Global Scope
Variables and functions declared outside of any function or block have global scope. Global variables and functions can be accessed from anywhere in the code including inside functions or blocks. They are accessible throughout the entire program, from the point of declaration until the end of the program.
Code
let gv = 5;
myFun();
function myFun() {
console.log(gv);
}
Output
Local Scope
Variables declared inside a function have local scope and are accessible only within that function. Function parameters also have local scope and are treated as local variables within the function. Local variables and function parameters are created each time the function is called and destroyed when the function completes execution.
Code
function Myloc() {
let var1 = "Hello";
console.log(var1);
}
//console.log(var1); // ReferenceError: var1 is not defined
Myloc();
Output
Nested Scope
- When functions are defined inside other functions, they create nested scopes
- Inner functions have access to variables declared in their containing (outer) functions as well as global variables
- However, outer functions do not have access to variables declared in inner functions
Example
Code
function outfun() {
var outvar1 = "I am variable in outer funtion";
function infun() {
var invar1 = "I am variable in outer funtion";
console.log(outvar1); // can access here
console.log(invar1); // can access here
}
infun();
// console.log(invar); // ReferenceError: invar is not defined
}
outfun();
Output
Block Scope
Variables declared with ‘let’ and ‘const’ have block scope which means they are only accessible within the block in which they are declared (EX: if, for, while)
Code
let a = 6;
if (a) {
let b = 5;
var c = 10;
const d = 20;
console.log("within block");
console.log("a=", a);
console.log("b=", b);
console.log("c=", c);
console.log("d=", d);
}
console.log("Outside block");
console.log("a=", a);
//console.log("b=", b);//ReferenceError: b is not defined
console.log("c=", c);
//console.log("d=", d); //ReferenceError: d is not defined
Output
Views: 10