Scope in JavaScript

Scope in JavaScript refers to the accessibility of variables, functions, and objects in certain parts of your code. It determines where variables and functions can be accessed or referenced.

Types of Scope in JavaScript

1. Global Scope

Variables declared outside of any function or block are in the global scope. Accessible from anywhere in the code.


let globalVar = "I am global";

function showGlobalVar() {
    console.log(globalVar); // Accessible here
}

showGlobalVar();
console.log(globalVar); // Accessible here too
    

2. Function Scope

Variables declared inside a function are in the function scope. Accessible only within the function where they are declared.


function myFunction() {
    let functionScopedVar = "I am inside a function";
    console.log(functionScopedVar); // Accessible here
}

myFunction();
// console.log(functionScopedVar); // Error: Not accessible here
    

3. Block Scope

Variables declared with let or const inside a block {} are in block scope. Accessible only within the block where they are defined.


{
    let blockScopedVar = "I am inside a block";
    console.log(blockScopedVar); // Accessible here
}

// console.log(blockScopedVar); // Error: Not accessible here
    

4. Lexical Scope

Inner functions can access variables of their parent functions due to lexical scoping.


function outerFunction() {
    let outerVar = "I am outer";

    function innerFunction() {
        console.log(outerVar); // Accessible due to lexical scoping
    }

    innerFunction();
}

outerFunction();
    

5. Module Scope (ES6+)

Variables defined in a module are scoped to that module and are not accessible globally. Modules use the import and export keywords.


// In module.js
export let moduleScopedVar = "I am in a module";

// In main.js
import { moduleScopedVar } from './module.js';
console.log(moduleScopedVar);