Series: JavaScript Basics Lesson 4

Scope

JavaScript'da Scope tushunchasini o'rganing: Global scope, Function scope, Block scope, Lexical scope va Scope Chain.

4-dars

🧠 Scope

1️⃣ Scope degani nima?

Scope — bu:

O'zgaruvchi (variable) qayerda ko'rinadi va qayerda ishlay oladi.

Agar scope bo'lmasa:

  • hamma joyda hamma narsa ko'rinib ketadi
  • katta loyihada tartibsizlik bo'ladi

2️⃣ JavaScript'da nechta scope bor?

JS'da 3 ta asosiy scope bor:

  1. Global scope
  2. Function scope
  3. Block scope

3️⃣ Global Scope

Global scope'da e'lon qilingan o'zgaruvchi:

  • faylning hamma joyidan ko'rinadi
  • ehtiyotsiz ishlatilsa — xavfli
let a = 10;

function test() {
  console.log(a);
}

test(); // 10

4️⃣ Function Scope

Funksiya ichida e'lon qilingan narsa:

  • faqat o'sha funksiya ichida yashaydi
function test() {
  let x = 5;
}

console.log(x); // ❌ ReferenceError

Bu function scope.

⚠️ var faqat shu scope'ni taniydi.

5️⃣ Block Scope

Block — bu { }.

let va const block scope bilan ishlaydi.

if (true) {
  let b = 20;
}

console.log(b); // ❌ ReferenceError

var esa block scope'ni tanimaydi:

if (true) {
  var c = 30;
}

console.log(c); // 30

6️⃣ Eng muhim joy — Lexical Scope

JS'da scope:

  • kod qayerda yozilganiga qarab belgilanadi
  • qayerda chaqirilganiga emas

Misol:

let x = 10;

function one() {
  console.log(x);
}

function two() {
  let x = 50;
  one();
}

two();

Natija:

10

Chunki one() global scope'da yozilgan.

Bu — lexical scope.

7️⃣ Scope Chain

Agar o'zgaruvchi topilmasa:

  1. Avval hozirgi scope
  2. Keyin tashqi scope
  3. Global'gacha
  4. Topilmasa → ReferenceError

Misol:

let global = "Global";

function outer() {
  let outerVar = "Outer";
  
  function inner() {
    let innerVar = "Inner";
    console.log(innerVar);  // Inner (hozirgi scope)
    console.log(outerVar); // Outer (tashqi scope)
    console.log(global);   // Global (global scope)
  }
  
  inner();
}

outer();

🔍 Mini-test

Quyidagi kod nima chiqaradi?

let a = 1;

function test() {
  let a = 2;
  if (true) {
    let a = 3;
    console.log(a);
  }
  console.log(a);
}

test();
console.log(a);

3 ta console.log bor.
Ular nimani chiqaradi?

Javob:

3
2
1

Tushuntirish:

  1. Birinchi console.log(a) — block scope ichida, a = 3 → 3
  2. Ikkinchi console.log(a) — function scope ichida, a = 2 → 2
  3. Uchinchi console.log(a) — global scope'da, a = 1 → 1

Har bir scope o'z o'zgaruvchisiga ega.

📝 Xulosa

  • Scope — o'zgaruvchining ko'rinish doirasi
  • 3 ta asosiy scope: Global, Function, Block
  • let va const block scope'ni qo'llab-quvvatlaydi
  • var faqat function scope'ni taniydi
  • Lexical scope — kod qayerda yozilganiga qarab belgilanadi
  • Scope Chain — ichki scope'dan tashqi scope'ga qarab qidirish