Two types of Scopes in JS

·

1 min read

1: Local Scope

Local scope refers to the context within which variables are declared inside functions or code blocks (e.g., loops, conditionals). Variables declared within a local scope are only accessible within that specific function or block and are not visible outside of it.

Ex:-

function myFunction() {

var localVar = "I'm a local variable";

console.log(localVar); // Accessible within the function }

myFunction();

console.log(localVar); // Error: localVar is not defined outside the function

2: Global Scope

Global scope refers to the outermost context of a JavaScript program or script. Variables declared in the global scope are accessible from anywhere in the code, including within functions and blocks.

Ex:-

var globalVar = "I'm a global variable";

function myFunction() {

console.log(globalVar); // Accessible from within the function

}

myFunction();

console.log(globalVar); // Accessible outside the function