Peter Kellner Peter Kellner - 1 year ago 47
Javascript Question

Checking JavaScript object for null subtelty

I believe I have found cases where I need to check for both undefined and null for a javascript object as follows:

if (x !== undefined && x != null && x.length > 0) {...}

However, in a recent upgrade of JetBrains tools, it tells me that this is sufficient

if (x != undefined && x.length > 0) {...}

My question is, I'm just wanting to insure that a string "x" has a length of non-zero and is not undefined or null (with the least amount tests).


Wex Wex
Answer Source

Checking if foo === undefined will trigger the error foo is not defined. See variable === undefined vs. typeof variable === "undefined"

The existential operator in CoffeeScript compiles to

typeof face !== "undefined" && face !== null


Matt's comment is better if you only want to check for strings:

typeof x === 'string' && x.length > 0