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

การประกาศ Block-Scoped Variables ใน JavaScript (let, const)

ใช้ let และ const (ES2015) ประกาศตัวแปร Block-Scoped เข้าถึงได้เฉพาะใน Block { } ที่ประกาศ

ตัวอย่าง

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Block Scoped Variables</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result, .sample { font-size: 20px; font-weight: 500; }
  </style>
</head>
<body>
  <h1>Declaring Block Scoped Variables</h1>
  <div class="sample"></div>
  <div style="color: green;" class="result"></div>
  <button class="Btn">CLICK HERE</button>
  <h3> Click to declare and display block scoped variables </h3>
  <script>
    let resEle = document.querySelector(".result");
    let sampleEle = document.querySelector(".sample");
    { // Block
      let a = 22;
      const b = 44;
      sampleEle.innerHTML = "let a = " + a + "<br>";
      sampleEle.innerHTML += "const b = " + b + "<br>";
    }
    document.querySelector(".Btn").addEventListener("click", () => {
      try {
        a + b; // ReferenceError
      } catch (err) {
        resEle.innerHTML = "a+b = " + err.message;
      }
    });
  </script>
</body>
</html>

คำอธิบาย

  • Block: { } ของ if, for, while, function, หรือ Block ธรรมดา
  • let a และ const b ใน Block → เข้าถึงได้แค่ใน Block
  • นอก Block → ReferenceError (TDZ - Temporal Dead Zone)
  • var ไม่มี Block Scope → Leak ออกมา
  • Loop: for (let i=0; i<3; i++) { ... } - i อยู่ใน Block Loop

ผลลัพธ์

In Block: let a = 22, const b = 44
Click: a+b = Cannot access 'a' before initialization