irusHacker irusHacker - 11 months ago 58
Javascript Question

How are these conditionals any different?

Why are these 2 conditionals different:


if (myObj !== null && typeof myObj !== "undefined")

Because of this, you must test typeof() first:


if (typeof myObj !== "undefined" && myObj !== null)

I pulled this off the w3schools site. According to w3schools you must test the typeof() first, why would this make a difference. The conditions look to be the same

Answer Source

The first condition will throw an error if the variable is undeclared.

ReferenceError: myObj is not defined

Note that the && operator is short-circuiting, so in the second condition, the myObj !== null expression will not be evaluated at all if myObj is undefined.

See here for details.