DEV Community

Visali Nedunchezhian
Visali Nedunchezhian

Posted on

JavaScript Scope

Scoping in JavaScript refers to the accessibility or visibility of variables, functions, and objects in some particular part of your code during runtime. JavaScript has several types of scope:

  • Global Scope
  • Function Scope
  • Block Scope

1. Global Scope

Variables declared outside of any function or block are in the global scope and are accessible anywhere in the code.

let globalVar = "I am global";

function test() {
  console.log(globalVar); // Accessible here
}

test();
console.log(globalVar); // Also accessible here
Enter fullscreen mode Exit fullscreen mode

** 2. Function Scope**

Variables declared inside a function are only accessible within that function.

function example() {
  let localVar = "I am local";
  console.log(localVar); // Accessible
}

example();
console.log(localVar); // ❌ ReferenceError
Enter fullscreen mode Exit fullscreen mode

3. Block Scope

Variables declared with let or const inside a block ({}) are only accessible within that block.

{
  let blockVar = "Inside block";
  console.log(blockVar); // Accessible here
}

console.log(blockVar); // ❌ ReferenceError
Enter fullscreen mode Exit fullscreen mode

Note: var does not have block scope—only function scope.

{
  var x = 10;
}
console.log(x); // ✅ 10
Enter fullscreen mode Exit fullscreen mode

Top comments (0)