Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Scope (Global vs. Local) in JavaScript


In JavaScript, scope refers to the context in which variables, functions, and objects are accessible or visible. Understanding scope is fundamental in JavaScript as it affects how variables and functions can be accessed and manipulated. In this article, we will explore the difference between global and local scope, with examples to clarify how they work.

1. Global Scope

A variable or function that is declared outside of any function or block is said to have a global scope. This means that it is accessible from anywhere in the code, including inside functions. In JavaScript, variables declared with the var keyword in the global context are added to the global object (i.e., window in browsers or global in Node.js).

Example: Global scope

      var globalVar = "I'm a global variable";

      function printGlobal() {
        console.log(globalVar); // Output: I'm a global variable
      }

      printGlobal();
    

In this example, the variable globalVar is declared in the global scope. The function printGlobal can access it because it is in the global scope, making it available throughout the entire code.

2. Local Scope

Local scope refers to variables that are declared inside a function or block. These variables are only accessible within the function or block in which they are declared. They are not accessible from outside of that scope. Variables declared using let and const have block scope, meaning they are only visible within the block they are declared in.

Example: Local scope

      function localScopeExample() {
        var localVar = "I'm a local variable";
        console.log(localVar); // Output: I'm a local variable
      }

      localScopeExample();
      console.log(localVar); // Error: localVar is not defined
    

In this example, localVar is declared inside the function localScopeExample and is only accessible within that function. Trying to access it outside the function results in an error because it has local scope.

3. Function Scope vs Block Scope

In JavaScript, there are two types of local scope: function scope and block scope. Function scope refers to variables declared inside a function using var, which are accessible throughout the entire function. Block scope refers to variables declared inside a block (e.g., inside loops or conditionals) using let or const, which are only accessible within that block.

Function Scope

Variables declared with var are function-scoped, meaning they are accessible anywhere within the function, even before the line where they are declared due to hoisting.

Example: Function scope with var

      function exampleFunction() {
        console.log(a); // Output: undefined (hoisting)
        var a = 10;
        console.log(a); // Output: 10
      }

      exampleFunction();
    

In this example, the variable a is hoisted to the top of the function, which is why we can log it before its actual declaration. However, its value is undefined before the assignment.

Block Scope

Variables declared with let and const are block-scoped, meaning they are only accessible within the block (e.g., within an if statement or for loop) in which they are declared.

Example: Block scope with let

      if (true) {
        let blockVar = "I'm a block-scoped variable";
        console.log(blockVar); // Output: I'm a block-scoped variable
      }

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

In this example, blockVar is only accessible within the if block. Attempting to access it outside the block results in an error because it is block-scoped.

4. Global Scope in the Browser

In the browser, when a variable is declared in the global scope using var, it is attached to the window object, which means it can be accessed globally. However, let and const do not add properties to the global object.

Example: Global scope in the browser

      var globalVar = "I'm a global variable";
      console.log(window.globalVar); // Output: I'm a global variable

      let globalLet = "I'm a global let";
      console.log(window.globalLet); // Output: undefined
    

In this example, globalVar is accessible via the window object, but globalLet is not, because variables declared with let do not become properties of the window object.

5. Closures and Scope

A closure is a function that retains access to variables from its lexical scope, even after the outer function has returned. Closures are a powerful feature in JavaScript and are often used for data encapsulation and creating private variables.

Example: Closures and scope

      function outer() {
        let outerVar = "I'm from the outer function";

        return function inner() {
          console.log(outerVar); // Accesses outerVar from outer function's scope
        };
      }

      const closureExample = outer();
      closureExample(); // Output: I'm from the outer function
    

In this example, the inner function has access to the outerVar variable from the outer function's scope, even after outer has finished executing. This is a closure in action.

Summary of Scope (Global vs. Local)

Conclusion

Understanding scope is essential for writing effective JavaScript code. By differentiating between global and local scopes, you can avoid issues like variable conflicts and unintended side effects. JavaScript's scope mechanisms, especially closures and block scoping with let and const, allow for more control and cleaner code.





Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java