Scope

Scope in Node.js defines where variables and functions can be accessed in your code. It includes global scope, block scope, and module scope. Lexical scope.


1. Global Scope

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

let globalVar = 'I am global';

2. Function Scope

Variables declared within a function are only accessible inside that function.

function myFunction() {
    let functionVar = 'I am inside a function';
    console.log(functionVar);
}

3. Block Scope

Variables declared with let or const inside {} are block-scoped, meaning they are only accessible within that block.

if (true) {
    let blockVar = 'I am inside a block';
    console.log(blockVar);
}

4. Module Scope

Each Node.js file is treated as a separate module. Variables declared are local to that module, not accessible globally.

// In module1.js
let moduleVar = 'I am in a module';

5. Lexical Scope

Functions can access variables from their outer scope. Scope is determined at the time of writing code, not execution.

function outerFunction() {
    let outerVar = 'I am outer';
    function innerFunction() {
        console.log(outerVar);
    }
    innerFunction();
}

6. Closure

Functions retain access to their scope even after the outer function has returned, forming a closure.

function createCounter() {
    let count = 0;
    return function() {
        count++;
        return count;
    };
}
const counter = createCounter();
counter(); // 1
counter(); // 2

You Might Also Like

Arrow Functions

### 1. Basic Syntax ``` const add = (a, b) => a + b; ``` ### 2. Single Parameter ``` const greet =...

Toggle Classes Based on Conditions

Use classList.toggle to add or remove classes based on a condition. ``` const button = document.get...