เพื่อตรวจสอบว่าตัวแปรมีอยู่ใน JavaScript ต้องตรวจสอบกับ null และ undefined ดังโค้ด ตรวจสอบตัวแปร myVar:
<html>
<body>
<script>
var myVar = 20;
if (myVar !== undefined && myVar !== null) {
document.write("Variable exists");
}
</script>
</body>
</html>
วิธีที่แนะนำ (Best Practices)
// 1. ตรวจสอบว่า variable ถูกประกาศใน scope นี้ (ไม่โยน ReferenceError)
typeof myVar !== 'undefined'
// 2. ตรวจสอบว่า property มีอยู่ใน object
'prop' in obj // true ถ้ามี property (รวม prototype)
obj.hasOwnProperty('prop') // true ถ้ามี own property เท่านั้น
// 3. Optional chaining (ES2020) - ปลอดภัยสำหรับ nested property
obj?.prop?.nested
// 4. Nullish coalescing (ES2020) - default value เมื่อ null/undefined
const value = obj?.prop ?? 'default';
หลีกเลี่ยงการใช้ if (myVar) เพราะค่า 0, "", false, NaN จะถูกถือว่า "ไม่มีอยู่" ซึ่งอาจผิดเจตนา