DEV Community

Cover image for Scop in Javascript with example
ratul hasan
ratul hasan

Posted on

Scop in Javascript with example

Scope in JavaScript refers to the visibility and accessibility of variables, functions, and objects in different parts of your code. JavaScript has three main types of scope:

  1. Global scope
  2. Function scope
  3. Block scope (introduced in ES6 with let and const)

Here's an example demonstrating these scopes:

// Global scope
let globalVar = "I'm global";

function exampleFunction() {
  // Function scope
  let functionVar = "I'm function-scoped";

  if (true) {
    // Block scope
    let blockVar = "I'm block-scoped";
    var functionScopedVar = "I'm function-scoped too";

    console.log(globalVar);  // Accessible
    console.log(functionVar);  // Accessible
    console.log(blockVar);  // Accessible
    console.log(functionScopedVar);  // Accessible
  }

  console.log(globalVar);  // Accessible
  console.log(functionVar);  // Accessible
  console.log(functionScopedVar);  // Accessible
  // console.log(blockVar);  // Error: blockVar is not defined
}

exampleFunction();

console.log(globalVar);  // Accessible
// console.log(functionVar);  // Error: functionVar is not defined
// console.log(blockVar);  // Error: blockVar is not defined
// console.log(functionScopedVar);  // Error: functionScopedVar is not defined
Enter fullscreen mode Exit fullscreen mode

Top comments (0)