Consider creating a string like this:
if(String(one) === 'undefined') {
// returns true for undefined and 'undefined'
}
Below are some points to keep in mind.
The first approach, involving creating a string, avoids false positives for other falsey values such as null
and false
, but it may be slightly harder to grasp at first glance.
The second method, which uses two comparisons, is easier to understand but comes with the drawback of potential false positives for falsey values like null
, 0
, and false
.
The third option, requiring more complex comparisons, is clearer to comprehend but results in a longer expression.
const one = undefined;
const two = 'undefined';
const three = 0;
// using the string creation method
if(String(one) === 'undefined') console.log("one is undefined");
if(String(two) === 'undefined') console.log("two is undefined");
if(String(three) === 'undefined') console.log("three is undefined");
// using two checks; easier to understand but may yield false positives
if(!one || one === 'undefined') console.log("one is undefined");
if(!two || two === 'undefined') console.log("two is undefined");
if(!three || three === 'undefined') console.log("three is undefined"); // false positive
// using two checks; easier to understand but with a longer expression
if(one === undefined || one === 'undefined') console.log("one is undefined");
if(two === undefined || two === 'undefined') console.log("two is undefined");
if(three === undefined || three === 'undefined') console.log("three is undefined");