The correct ways to check for an undefined value in JavaScript are:
1. Using typeof:
This approach is the most robust and safe, especially when dealing with undeclared variables.
if (typeof variable === 'undefined') {
console.log('Variable is undefined');
}
2. Using void 0:
if (variable === void 0) {
console.log('Variable is undefined');
}
Reason to use void 0:
It guarantees a value of undefined because void always evaluates to undefined.
Avoids accidental overwriting of the global undefined.