Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

JavaScript รองรับ Block Scope หรือไม่?

JavaScript รองรับ Block Scope สำหรับตัวแปรที่ประกาศด้วย let และ const เท่านั้น ส่วน var เป็น Function Scope ไม่มี Block Scope

ตัวอย่างโค้ด

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Block Scope Demo</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 20px; font-weight: 500; color: blueviolet; }
  </style>
</head>
<body>
  <h1>Block Scope ใน JavaScript</h1>
  <div class="result"></div>
  <br />
  <button class="Btn">คลิกที่นี่</button>
  <h3>คลิกปุ่มด้านบนเพื่อสร้างตัวแปร var และ let แล้วลองเข้าถึง</h3>
  <script>
    const resEle = document.querySelector(".result");
    const BtnEle = document.querySelector(".Btn");
    
    { // Block 1
      let a = 22; // Block scoped
    }
    
    { // Block 2
      var b = 44; // Function scoped!
    }
    
    BtnEle.addEventListener("click", () => {
      try {
        resEle.innerHTML = a; // Error: a is not defined
      } catch (err) {
        resEle.innerHTML = err + "<br>"; // ReferenceError: a is not defined
      }
      resEle.innerHTML += "var b = " + b; // 44 - เข้าถึงได้!
    });
  </script>
</body>
</html>

สรุป Scope ใน JavaScript

KeywordScope TypeHoistingTemporal Dead Zone
varFunction Scope✅ (undefined)❌
letBlock Scope✅ (TDZ)✅
constBlock Scope✅ (TDZ)✅

Block Scope คืออะไร?

Block คือโค้ดที่อยู่ใน { ... } เช่นใน if, for, while, หรือแค่ { } เดี่ยวๆ ตัวแปร let/const จะมีอยู่เฉพาะใน Block นั้นๆ

if (true) {
  let x = 1;
  const y = 2;
  var z = 3;
}
console.log(x); // ReferenceError
console.log(y); // ReferenceError
console.log(z); // 3 - var ทะลุ block!

ผลลัพธ์

Error: "a is not defined" สำหรับ let, แต่ "var b = 44" เข้าถึงได้ปกติ