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

การสร้าง Constants ใน JavaScript ด้วย const

ใช้ Keyword const ประกาศ Constant (ค่าคงที่) ไม่สามารถ Reassign ได้ แต่ Object/Array ที่ประกาศด้วย const ยังแก้ไข Property/Element ได้

ตัวอย่าง

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
  </style>
</head>
<body>
  <h1>Const Example</h1>
  <button class="Btn">CLICK HERE</button>
  <p class="sample"></p>
  <h3> Click to try changing const value </h3>
  <script>
    let sampleEle = document.querySelector(".sample");
    const a = 33;
    sampleEle.innerHTML = "a = " + a + "<br>";
    document.querySelector(".Btn").addEventListener("click", () => {
      try {
        a = 44; // Error: Assignment to constant variable
      } catch (err) {
        sampleEle.innerHTML += "Error: " + err;
      }
    });
  </script>
</body>
</html>

คำอธิบาย

  • const a = 33 - ไม่สามารถ a = 44 ได้ (TypeError)
  • แต่ const obj = {x: 1} → obj.x = 2 ได้ (Mutate Property)
  • const arr = [1] → arr.push(2) ได้
  • ต้องกำหนดค่าเริ่มต้นตอนประกาศ
  • Block-scoped (เหมือน let)

ผลลัพธ์

ก่อนกด: "a = 33" | หลังกด: "Error: TypeError: Assignment to constant variable"