Programming Track
JavaScript
Primitive Types
null
เรียนรู้ `null` สำหรับการบอกว่าไม่มีค่าแบบตั้งใจ วิธีใช้กับ empty state และความต่างจาก `undefined`
null คือไม่มีค่าแบบตั้งใจ
`null` คือ primitive value ที่ใช้บอกว่า “ตอนนี้ไม่มีค่า” แบบตั้งใจ เราเป็นคนกำหนดเองว่าตัวแปรนี้ยังว่างอยู่ ใช้บ่อยกับ state ที่รอข้อมูล เช่น ยังไม่ได้เลือกสินค้า ยังไม่มีผู้ใช้ล็อกอิน หรือยังไม่มีผลลัพธ์
ตั้งค่าเริ่มต้นเป็น nullJS
let selectedProduct = null;
let currentUser = null;
console.log(selectedProduct); // null
console.log(currentUser); // nullnull ต่างจาก undefined
`null` แปลว่าเราตั้งใจให้ไม่มีค่า ส่วน `undefined` มักแปลว่ายังไม่ได้กำหนดค่า ข้อควรระวังคือ `typeof null` ได้ `"object"` ซึ่งเป็นพฤติกรรมเก่าของ JavaScript ให้ตรวจ `null` ด้วย `value === null` แทน
ตรวจ null แบบตรงตัวJS
let selectedProduct = null;
let productName;
console.log(selectedProduct === null); // true
console.log(productName === undefined); // true
console.log(typeof null); // "object"- ใช้ `null` เมื่ออยากสื่อว่าไม่มีค่าแบบตั้งใจ
- ตรวจ `null` ด้วย `=== null`
- อย่าใช้ `typeof` เพื่อตัดสินว่าเป็น `null`