Types of Scopes in javascript
Tags: webdev, javascript, programming, beginners
Published: 2024-06-15 14:36:32

In JavaScript, scope determines the accessibility or visibility of variables and functions at various parts of the code during execution. Understanding the different types of scopes in JavaScript is crucial for writing efficient and error-free code. Here are the primary types of scopes in JavaScript:

1. **Global Scope**
Definition: Variables declared outside any function or block have global scope, meaning they are accessible from anywhere in the code.
Creation: Variables become global if they are declared with var outside any function or if they are not declared with let, const, or var inside a function (implicitly global).

`var globalVar = 'I am a global variable';

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

displayGlobalVar();
console.log(globalVar); // Accessible here too
`

2. **Local Scope (Function Scope)**
Definition: Variables declared within a function are in the local scope (or function scope). They are only accessible within that function.
Creation: Any variable declared inside a function using var, let, or const.

`function myFunction() {
    var localVar = 'I am a local variable';
    console.log(localVar); // Accessible here
}

myFunction();
console.log(localVar); // Uncaught ReferenceError: localVar is not defined
`

3. **Block Scope**
Definition: Variables declared within a block (denoted by {}) are only accessible within that block. This type of scope was introduced with ES6 and applies to variables declared using let and const.
Creation: Any variable declared inside a block using let or const.

`{
    let blockVar = 'I am a block-scoped variable';
    const blockConst = 'I am also block-scoped';
    console.log(blockVar); // Accessible here
    console.log(blockConst); // Accessible here
}

console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined
console.log(blockConst); // Uncaught ReferenceError: blockConst is not defined
`

4. **Lexical Scope (Static Scope)**
Definition: Lexical scope means that the accessibility of variables is determined by their physical location in the code at the time of writing. Inner functions have access to variables defined in outer functions.
Creation: Automatically created based on where functions are declared.

`function outerFunction() {
    var outerVar = 'I am an outer variable';

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

    innerFunction();
}

outerFunction();
`

5. **Module Scope**
Definition: Variables declared within a module (using the ES6 module system) are scoped to that module. They are not accessible outside the module unless explicitly exported.
Creation: Using import and export statements in ES6 modules.

`// module1.js
export const moduleVar = 'I am a module-scoped variable';

// main.js
import { moduleVar } from './module1.js';
console.log(moduleVar); // Accessible here
`

**Scope Chain**
The scope chain is a hierarchical structure that determines the order in which scopes are looked up to resolve variable names. When a variable is referenced, JavaScript starts looking in the current scope, then moves up to the outer scope, and continues this process until it reaches the global scope.

`var globalVar = 'I am global';

function outerFunction() {
    var outerVar = 'I am outer';

    function innerFunction() {
        var innerVar = 'I am inner';
        console.log(innerVar); // Found in inner scope
        console.log(outerVar); // Found in outer scope
        console.log(globalVar); // Found in global scope
    }

    innerFunction();
}

outerFunction();
`

**Closures**
Closures are functions that remember their lexical scope even when they are executed outside of that scope. This allows inner functions to access variables from their outer function scope even after the outer function has returned.

`function outerFunction() {
    var outerVar = 'I am outer';

    function innerFunction() {
        console.log(outerVar);
    }

    return innerFunction;
}

const closureFunction = outerFunction();
closureFunction(); // 'I am outer' - outerVar is still accessible
`

**Summary**
Understanding these different types of scopes and their behavior is essential for managing variable accessibility and preventing issues like variable shadowing and unintentional global variable creation. It also helps in writing clean, maintainable, and error-free JavaScript code.