Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีตรวจสอบว่าตัวแปรเป็น 'undefined' หรือ 'null'

จากผลลัพธ์ของโค้ดต่อไปนี้ สามารถทราบได้ว่าตัวแปรเป็น null หรือ undefined หากผลลัพธ์เป็น "false" หมายถึงตัวแปรเป็น null และ undefined

ที่นี่ตัวแปรให้ผลลัพธ์ "True":

<html> 
  <body> 
    <script> 
      var age = 10; 
      if (age) { 
        document.write("True"); 
      } else { 
        document.write("False"); 
      } 
    </script> 
  </body> 
</html>

วิธีตรวจสอบที่ถูกต้องและชัดเจน

// 1. ตรวจสอบ undefined (ไม่ได้ประกาศ หรือ ประกาศแต่ไม่กำหนดค่า)
typeof myVar === 'undefined'  // true ถ้า undefined

// 2. ตรวจสอบ null (กำหนดค่าว่างโดยเจตนา)
myVar === null  // true ถ้า null

// 3. ตรวจสอบทั้งคู่ (null หรือ undefined) - ใช้ == (loose equality)
myVar == null   // true ถ้า null หรือ undefined (แนะนำสำหรับกรณีนี้)

// 4. Nullish coalescing (ES2020) - default value
const value = myVar ?? 'default';

// 5. Optional chaining (ES2020) - เข้าถึง property อย่างปลอดภัย
obj?.prop?.nested

ตารางเปรียบเทียบ

Expressionundefinednull0""false
if (x)FalseFalseFalseFalseFalse
x == nullTrueTrueFalseFalseFalse
x === nullFalseTrueFalseFalseFalse
typeof x === 'undefined'TrueFalseFalseFalseFalse