Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 926
uniqUsername Avatar asked Sep 11 '16 19:09

uniqUsername


1 Answers

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.

like image 77
Tomas Nikodym Avatar answered Sep 22 '22 20:09

Tomas Nikodym