ใช้คำสำคัญ const (ES6+)
ECMAScript 2015 (ES6) เพิ่ม const สำหรับประกาศ Constant (ค่าคงที่) ไม่สามารถ Reassign ได้
Syntax
const MY_CONSTANT = 5; // MY_CONSTANT = 10; // TypeError: Assignment to constant variable
ตัวอย่างโค้ด
const MY_VAL = 5; // กำหนดค่าคงที่ 5 // MY_VAL = 10; // Error: Assignment to constant variable
รายละเอียดสำคัญ
- Block Scoped: เหมือน
letจำกัดขอบเขตใน Block{ } - ต้อง Initialize ทันที: ต้องกำหนดค่าในบรรทัดเดียวกับการประกาศ
- ไม่สามารถ Reassign:
MY_VAL = 10จะ Error (TypeError ใน Strict Mode) - Object/Array ที่เป็น Const ยัง Mutate ได้: Property/Element เปลี่ยนได้
ตัวอย่าง Object/Array Const
const MY_ARRAY = [1, 2, 3];
MY_ARRAY.push(4); // OK! Mutate ได้
MY_ARRAY[0] = 100; // OK!
// MY_ARRAY = []; // Error! Reassign ไม่ได้
const MY_OBJECT = { a: 1 };
MY_OBJECT.b = 2; // OK!
// MY_OBJECT = {}; // Error!
Naming Convention
慣例 (Convention) ใช้ UPPER_SNAKE_CASE สำหรับ Constants:
const MAX_USERS = 100; const API_BASE_URL = "https://api.example.com"; const DEFAULT_TIMEOUT = 5000; const COLORS = ["red", "green", "blue"];
Object.freeze() - Deep Immutable
ถ้าต้องการ Object/Array ที่ Immutable จริงๆ (Deep Freeze):
const CONFIG = Object.freeze({
API_URL: "https://api.example.com",
MAX_RETRIES: 3,
COLORS: Object.freeze(["red", "green", "blue"])
});
// CONFIG.API_URL = "new"; // Error (Strict Mode) หรือ Silent Fail
// CONFIG.COLORS.push("yellow"); // Error/Silent Fail
Browser Support
const: ES6 (2015) - ทุก Browser สมัยใหม่, IE11+ (Partial)Object.freeze(): ES5 - ทุก Browser รวม IE9+
สรุป
ใช้ const กำหนด Constant ใน ES6+ Block Scoped ต้อง Initialize ทันที ไม่ Reassign ได้ แต่ Object/Array ยัง Mutate ได้ ต้องการ Deep Immutable ใช้ Object.freeze() Naming: UPPER_SNAKE_CASE