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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay