จากผลลัพธ์ของโค้ดต่อไปนี้ สามารถทราบได้ว่าตัวแปรเป็น null หรือ undefined หากผลลัพธ์เป็น "false" หมายถึงตัวแปรเป็น null และ undefined
ที่นี่ตัวแปรให้ผลลัพธ์ "True":
<html>
<body>
<script>
var age = 10;
if (age) {
document.write("True");
} else {
document.write("False");
}
</script>
</body>
</html>
ใช้ typeof เพื่อตรวจสอบว่าตัวแปรมีอยู่หรือไม่:
<html>
<body>
<script>
var age = 10;
if (typeof age !== 'undefined') {
document.write("True");
} else {
document.write("False");
}
</script>
</body>
</html>
วิธีตรวจสอบครอบคลุม (Comprehensive Check)
function isEmpty(value) {
// null, undefined
if (value == null) return true; // == null ครอบคลุมทั้ง null และ undefined
// String ว่างหรือ whitespace
if (typeof value === 'string' && value.trim() === '') return true;
// Array ว่าง
if (Array.isArray(value) && value.length === 0) return true;
// Object ว่าง (ไม่มี own properties)
if (typeof value === 'object' && Object.keys(value).length === 0) return true;
return false;
}
// ตัวอย่างการใช้งาน
console.log(isEmpty(null)); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty("")); // true
console.log(isEmpty(" ")); // true
console.log(isEmpty([])); // true
console.log(isEmpty({})); // true
console.log(isEmpty(0)); // false (0 เป็นค่าที่ valid)
console.log(isEmpty(false)); // false
สรุปการตรวจสอบ
| กรณี | โค้ด |
|---|---|
| undefined (ไม่ได้ประกาศ/ไม่ได้กำหนดค่า) | typeof x === 'undefined' |
| null | x === null |
| null หรือ undefined | x == null |
| empty string | x === '' หรือ x.trim() === '' |
| empty array | Array.isArray(x) && x.length === 0 |
| empty object | Object.keys(x).length === 0 |