เพื่อตรวจสอบตัวแปรว่า 'undefined' ต้องตรวจสอบดังนี้ หากผลลัพธ์เป็น "false" หมายถึงตัวแปรไม่ได้ถูกกำหนด ที่นี่ตัวแปรให้ผลลัพธ์ "True" คือ defined:
ตัวอย่าง
Live Demo
<html>
<body>
<script>
var rank = 1;
if (rank) {
document.write("True");
} else {
document.write("False");
}
</script>
</body>
</html>
วิธีที่ถูกต้องและแม่นยำ
// 1. ตรวจสอบว่า variable ถูกประกาศใน scope (ไม่โยน ReferenceError)
typeof myVar !== 'undefined' // แนะนำ - ไม่โยน error ถ้ายังไม่ประกาศ
// 2. ตรวจสอบว่า property มีอยู่ใน object
'prop' in obj // true ถ้ามี (รวม prototype chain)
obj.hasOwnProperty('prop') // true ถ้ามี own property เท่านั้น
Object.hasOwn(obj, 'prop') // ES2022 - แนะนำแทน hasOwnProperty
// 3. ตรวจสอบค่าไม่เป็น null/undefined
myVar != null // loose equality - true ถ้าไม่ใช่ null และ undefined
myVar !== null && myVar !== undefined // strict
// 4. Optional chaining + nullish coalescing (ES2020)
const value = obj?.prop ?? 'default';
⚠️ ข้อผิดพลาดทั่วไป
// ผิด - โยน ReferenceError ถ้ายังไม่ประกาศ
if (myVar) { ... }
// ถูกต้อง - ไม่โยน error
if (typeof myVar !== 'undefined') { ... }