Sobes.tech
Junior

What is the scope of variables in JavaScript?

sobes.tech AI

Answer from AI

Scope defines the accessibility of variables, functions, and objects within a certain part of the code.

In JavaScript, there are several types of scope:

  • Global Scope: Variables declared outside of any functions or blocks are accessible from any part of the code.
  • Function Scope: Variables declared inside a function (before ES6) are only accessible within that function and its nested functions.
  • Block Scope: Variables declared with let and const inside blocks (e.g., {} or loops) are only accessible within that block.

Example:

// Global scope
let globalVar = "I am global";

function someFunction() {
  // Function scope (before ES6)
  var functionVar = "I am inside a function";
  console.log(globalVar); // Accessible global variable

  if (true) {
    // Block scope (for let and const)
    let blockVar = "I am inside a block";
    console.log(functionVar); // Accessible function variable
    console.log(blockVar); // Accessible block variable
  }

  // console.log(blockVar); // Error: blockVar is not accessible here
}

someFunction();
// console.log(functionVar); // Error: functionVar is not accessible here

Keywords for declaring variables and their impact on scope:

Keyword Scope before ES6 Scope after ES6
var Function scope Function scope
let - Block scope
const - Block scope

Understanding scope is critical for preventing variable name conflicts and writing clean, predictable code.