JS Scopes

Overview

Scope refers to the context in which variables and functions are declared and accessed in JavaScript. It determines the visibility and lifetime of these identifiers.

Global Scope

Variables declared outside of any function or block have global scope, making them accessible from anywhere in the script.

Try yourself
        
            let globalVariable = "I am global";

function printGlobal() {
    console.log(globalVariable); // Accessible inside the function
}
printGlobal()
console.log(globalVariable); // Accessible outside the function
        
    

Local (Function) Scope

Variables declared within a function have local scope, meaning they are only accessible within that function.

Try yourself
        
            function scopeExample() {
    var localVar = "I'm local!";
    console.log(localVar);   // Outputs: I'm local! (Accessible)
}
scopeExample()
console.log(localVar);       // Error: localVar is not defined. (Not accessible)
        
    

Block Scope (ES6)

Introduced in ES6, let and const have block scope, meaning they are confined to the nearest enclosing block (e.g., if, for, or {}).

Try yourself
        
            function exampleFunction() {
   if (true) {
      var x = 10; // Function-scoped variable
      let y = 20; // Block-scoped variable
      const z = 30; // Block-scoped variable
   }

   console.log(x); // Outputs 10, x is accessible due to function scope
   console.log(y); // Throws an error, y is not accessible outside the block
   console.log(z); // Throws an error, z is not accessible outside the block
}

exampleFunction();
        
    

Scope Chain

JavaScript uses a scope chain to resolve variable names. If a variable is not found in the current scope, the engine looks up the chain until it finds the variable or reaches the global scope.

Try yourself
        
            let x = 40;

function outer() {
    let y = 50;

    function inner() {
        let z = 60;
        console.log(x + y + z);  // Accessible: 150
    }

    inner();
}

outer();
console.log(x + y);  // Not accessible
        
    

Global Variables

Variables declared without var, let, or const become global variables, even if declared inside a function.

Try yourself
        
            function createGlobalVar() {
    globalVar = 80;  // Becomes a global variable
}

createGlobalVar();
console.log(globalVar);  // Accessible: 80
        
    

Scope Best Practices


Summary

Understanding JavaScript scopes is crucial for managing variables and functions effectively. Scopes define where identifiers are accessible and help prevent naming conflicts.