JavaScript : Scope

In JavaScript, scope refers to the visibility and accessibility of variables and functions within a program. Understanding scope is crucial for writing maintainable and bug-free code. There are two main types of scope in JavaScript: local (or function) scope and global scope.

1. Local (Function) Scope:


Variables declared inside a function are scoped to that function and are not accessible outside of it. This means they have local scope.


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

myFunction(); // Output: I am a local variable
console.log(localVar); // ReferenceError: localVar is not defined

 

2. Block Scope (with let and const):


Variables declared with let and const keywords have block scope, which means they are scoped to the nearest enclosing block (usually a pair of curly braces {} ). This includes loops ( for , while , do...while ), if statements, and functions.


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

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

3. Global Scope:


Variables declared outside of any function or block have global scope. They can be accessed from anywhere in the code, including inside functions and blocks.


var globalVar = 'I am a global variable';

function myFunction() {
    console.log(globalVar);
}

myFunction(); // Output: I am a global variable
console.log(globalVar); // Output: I am a global variable

 

4. Lexical Scope:


JavaScript uses lexical (or static) scope, which means the scope of a variable is determined by its position within the code. When a variable is referenced, JavaScript looks for the variable's declaration in the current scope and then moves up the nested scopes until it finds the variable or reaches the global scope.


var globalVar = 'Global';

function outerFunction() {
    var outerVar = 'Outer';

    function innerFunction() {
        var innerVar = 'Inner';
        console.log(globalVar, outerVar, innerVar); // Accessible
    }

    innerFunction();
    console.log(globalVar, outerVar, innerVar); // ReferenceError: innerVar is not defined
}

outerFunction();
 

5. Scope Chain:


The scope chain refers to the hierarchical structure of scopes in JavaScript. Each function creates a new scope, and nested functions have access to variables in their outer (enclosing) scopes. This forms a chain of nested scopes.

Understanding scope and the scope chain is fundamental to writing JavaScript code that behaves as expected. It helps prevent unintended variable collisions and aids in writing cleaner, more modular code.