1

I am using node backend. I have some typescript code where I have a variable that sometimes print as string 'undefined' instead of just being undefined (in some cases). Is there a single clean check to ensure that the variable is NOT equal to 'undefined' and undefined. It doesnt look very clean to do it like: if (xxx && xxx!= 'undefined') {}

user1892775
  • 1,533
  • 2
  • 28
  • 41

1 Answers1

0

You could create a string:

if(String(one) === 'undefined') {
    // true for undefined and 'undefined'
}

Here are some things to consider.

The first option, which creates a string, has the benefit of not giving false positives for other falsey values such as null and false and has the cost of perhaps being harder to understand.

The second option, which performs two comparisons, has the benefit of being easier to understand and has the cost of giving false positives for falsey values such as null, 0, and false.

The third option, which performs more involved comparisons, has the benefit of being easier to understand and the cost of being a longer expression.

const one = undefined;
const two = 'undefined';
const three = 0;

// creating a new string
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");

// doing two checks; this seems easier to understand
// but returns 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

// doing two checks; this seems easier to understand
// but the expression is longer
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");
Community
  • 1
  • 1
Shaun Luttin
  • 107,550
  • 65
  • 332
  • 414