JS Tutorial



JS SCOPE


JavaScript Scope ๐ŸŽฏ

Scope determines the accessibility (visibility) of variables. In JavaScript, there are different types of scope:

  • Global Scope
  • Function Scope
  • Block Scope (with let and const)

๐ŸŒ Global Scope

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

let globalVar = "Hello";

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

๐Ÿ” Function Scope

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

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

console.log(localVar); // โŒ Error: not defined

๐Ÿ“ฆ Block Scope (let & const)

Variables declared with let or const inside { } are limited to that block.

{
  let blockVar = "Inside block";
  console.log(blockVar); // โœ… Works
}
console.log(blockVar); // โŒ Error

๐Ÿงช Live Scope Tester

๐Ÿ’ก Scope Summary

  • var is function-scoped, not block-scoped.
  • let and const are block-scoped.
  • Global variables are accessible anywhere, but use with care!
Tip: Keep variables scoped as tightly as possible to avoid bugs and conflicts.

๐ŸŒŸ Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review