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

มี Constants ใน JavaScript หรือไม่?

มี constants ใน JavaScript ค่าของ const คงที่ ไม่สามารถเปลี่ยนแปลงหรือประกาศซ้ำได้ สร้าง read-only reference ด้วยการประกาศ const

const MY_CONSTANT = "some-value";

ด้วย const คุณสามารถประกาศตัวแปร local ด้วย block scope แทน function scope สมมติว่ามีตัวแปรคงที่ a หลังจากประกาศค่าเป็น constant แล้ว ไม่สามารถกำหนดค่าใหม่ให้ได้

// ประกาศ 'a' เป็น constant variable
const a = 150; 
// การกำหนดค่าใหม่ให้ 'a' จะล้มเหลว
a = 0;     // TypeError
a++;       // TypeError
// การประกาศด้านล่างไม่ทำงาน
var a = 0; // SyntaxError

ข้อสังเกตสำคัญ

  • const ทำให้ binding เป็น immutable — ไม่ใช่ value
  • Object/Array ที่ประกาศด้วย const ยังแก้ไขได้ภายใน:
    const arr = [1, 2];
    arr.push(3);  // OK
    arr[0] = 99;  // OK
    // arr = [];   // TypeError
    
    const obj = { x: 1 };
    obj.x = 2;    // OK
    obj.y = 3;    // OK
    // obj = {};   // TypeError
  • ใช้ Object.freeze() สำหรับ shallow freeze, หรือ library เช่น Immer, immer สำหรับ deep immutability
  • Convention: CONSTANTS ใช้ UPPER_SNAKE_CASE