ทั้งสองแทน "ไม่มีค่า" แต่มี ความตั้งใจและต้นกำเนิด ที่แตกต่างกัน
ทั้งสองแทน "ไม่มีค่า" แต่มี ความตั้งใจและต้นกำเนิด ที่แตกต่างกัน
undefined: ความไม่มีอยู่ ของค่า โดยปกติถูกกำหนดโดย JavaScript engine — ตัวแปรที่ประกาศแต่ยังไม่มีการกำหนดค่า property ของ object ที่หายไป parameter ของ function ที่คุณไม่ได้ส่ง หรือ function ที่ไม่มี returnnull: ค่า "ว่าง" ที่ ตั้งใจ ซึ่ง คุณ กำหนดเพื่อบอกว่า "จงหมายถึงไม่มีอะไรเลยที่นี่"let a; // undefined — declared, not assigned
const obj = {};
obj.missing; // undefined — property doesn't exist
function f() {}
f(); // undefined — no return
const b = null; // null — you chose to empty it
null == undefined; // true — loose equality treats them as equal
null === undefined; // false — different types
typeof undefined; // "undefined"
typeof null; // "object" (historical bug)
const value = input ?? "default"; // defaults on EITHER null or undefined
user?.address?.city; // optional chaining — undefined if any link is null/undefined
ใช้ null เพื่อลบค่าอย่างตั้งใจ (เช่น "ไม่มีผู้ใช้ที่เลือก") และถือว่า undefined เป็น "ยังไม่ได้กำหนด" ตัวดำเนิน ?? (nullish coalescing) และ ?. (optional chaining) จัดการทั้งสองอย่างพร้อมกัน ซึ่งเป็นเหตุผลที่ใช้กันอย่างแพร่หลาย
คลังคำถามสัมภาษณ์งาน IT พร้อมคำตอบโดยละเอียด — ตั้งแต่ระดับ Junior ถึง Senior
บริจาค