Search code examples
javascripttypeof

Short if with typeof gives unexpected results


The following code:

var isBlacklisted = (typeof item.is_blacklisted == "undefined" ? false : true);
console.log(typeof item.is_blacklisted == "undefined");
console.log(isBlacklisted);

outputs:

false true

No matter if is_blacklisted is actually undefined or not, in both cases it's always same results.

Now I also tried doing:

  • var isBlacklisted = typeof item.is_blacklisted == "undefined" ? false : true;
  • var isBlacklisted = (typeof item.is_blacklisted == "undefined" ? false : true);
  • var isBlacklisted = (typeof item.is_blacklisted === "undefined" ? false : true);

And had the exact same results. I can't seem to figure out what is wrong there, any insights? PLEASE CHECK OUT FIDDLE

Fiddle


Solution

  • The result right after the ? is what you get if your condition is true. Since your condition is indeed true, the ternary operator results in false. In order to get it working, just swap true and false on your ternary:

    var isBlacklisted = (typeof item.is_blacklisted == "undefined" ? true : false)
    

    Or don't even use a ternary in first place, since you're working with booleans:

    var isBlacklisted = typeof item.is_blacklisted == "undefined"
    

    EDIT

    I just checked your fiddle and I see you're setting your attribute to null, which is not the same thing as undefined. typeof null returns object, not undefined. . This may be the reason of your confusion. If you set it as undefined instead of null, you'll get the result you want.