irusHacker irusHacker - 2 months ago 8
Javascript Question

How are these conditionals any different?

Why are these 2 conditionals different:

Incorrect:

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


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

Correct:

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

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.

Comments