Spex3
    

JavaScript Scope 🔍


    

    

JavaScript Scope 🔍
Scope determines where variables can be accessed in your code. There are three main types of scope in JavaScript:

1️⃣ Global Scope 🌎
2️⃣ Local (Function) Scope 🔒
3️⃣ Block Scope 📦

1️⃣ Global Scope 🌎
A global variable is declared outside of any function or block.

It is accessible anywhere in the script.

✅ Example:

 
let globalVar = "I am global!";

function showGlobal() {
console.log(globalVar); // Accessible inside the function
}

showGlobal();
console.log(globalVar); // Accessible outside the function

🛑 Caution: Global variables can be modified anywhere, which may cause unexpected behavior in large projects.

2️⃣ Local (Function) Scope 🔒
A variable declared inside a function is only accessible within that function.

✅ Example:
 
function localExample() {
let localVar = "I am local!";
console.log(localVar); // ✅ Works inside function
}

localExample();
console.log(localVar); // ❌ Error: localVar is not defined

3️⃣ Block Scope 📦 (ES6: let & const)
A block is a section of code enclosed in {}.

Variables declared with let or const inside a block cannot be accessed outside.

var does NOT have block scope! (It gets hoisted to the function or global scope.)

✅ Example:
 
{
let blockScoped = "Inside block";
console.log(blockScoped); // ✅ Works inside block
}

console.log(blockScoped); // ❌ Error: blockScoped is not defined
❌ var does NOT obey block scope!
 
{
var noBlockScope = "I'm using var!";
}
console.log(noBlockScope); // ✅ Accessible (not block-scoped)


4️⃣ Summary Table 📜
Scope Type Declared Using Accessible Where? Example
Global Scope var, let, const Anywhere in the script Declared outside functions
Local (Function) Scope var, let, const Only inside the function Declared inside a function
Block Scope let, const Only inside {} block Declared inside {}
5️⃣ Quick Quiz 🎯
What will be logged to the console?

 
function testScope() {
if (true) {
let message = "Hello!";
}
console.log(message);
}

testScope();

❓ Answer: Error! message is block-scoped and not accessible outside the if block.


    Date: 2025-03-29 00:00:00.000000