Engineering note · Node.js

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.

By Published

Node.js

1. Global Scope

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

CODE SAMPLE Code snippet
let globalVar = 'I am global';

2. Function Scope

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

CODE SAMPLE Code snippet
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.

CODE SAMPLE Code snippet
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.

CODE SAMPLE Code snippet
// 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.

CODE SAMPLE Code snippet
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.

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

More engineering notes

Arrow Functions

Arrow functions in Node.js are a concise way to write functions. They are great for short, single-ex...

Functions : Declaration, Expression, IIFE, Callback and More

Functions are fundamental building blocks in Node.js, used to organize code and handle logic.