Sobes.tech
Junior

What is scope in JavaScript?

sobes.tech AI

Answer from AI

Scope in JavaScript is the context in which variables and functions are defined and accessible.

Simply put, it determines where in the code you can refer to a variable or function.

There are several types of scope:

  • Global Scope: Variables declared outside of any function are in the global scope. They are accessible from anywhere in the code.
    // Global variable
    let globalVar = "I am visible everywhere";
    
    function showGlobal() {
      console.log(globalVar); // Accessible inside the function
    }
    
    showGlobal();
    
  • Local (Function) Scope: Variables declared inside a function are in the local scope of that function. They are only accessible within that function and any nested functions, but not outside.
    function showLocal() {
      // Local variable
      let localVar = "I am only visible here";
      console.log(localVar);
    }
    
    showLocal();
    // console.log(localVar); // Error: localVar is not defined
    
  • Block Scope: Introduced in ES6 (ES2015) with let and const. Variables declared with let or const inside curly braces ({}), such as in blocks, loops, or conditional statements, have block scope. Variables declared with var do not have block scope.
    if (true) {
      // Variable with block scope
      let blockVar = "I am only visible in this block";
      console.log(blockVar);
    }
    
    // console.log(blockVar); // Error: blockVar is not defined
    
    for (let i = 0; i < 2; i++) {
      // Variable with block scope in a loop
      console.log(i);
    }
    
    // console.log(i); // Error: i is not defined (if let was used)
    

It is also important to understand the concept of Scope Chain. When JavaScript tries to find the value of a variable, it first looks in the current scope. If not found, it moves to the outer (parent) scope, and so on, up to the global scope. If the variable is not found even in the global scope, a ReferenceError is thrown.