Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if undefined and null in jQuery

I'm a bit confused when checking if null or undefined and if I should be using !== or != and "undefined" or undefined.

Here is some code I'm working on. Where am I going wrong with my null/unudefined etc?

var c = (jQuery(this).prop("target") != null && jQuery(this).prop("target") != undefined && jQuery(this).prop("target").toLowerCase() == "_blank") ? 1 : 0;

Thanks

like image 720
K Groll Avatar asked Feb 21 '13 06:02

K Groll


2 Answers

In general, keep it simple.

To check for undefined, use:

foo === undefined
foo !== undefined

To check for null, use:

foo === null
foo !== null

To check for either at the same time, use:

foo == null
foo != null

And in any case, store your .prop() to a variable to keep it clean. But in your case, if it equals "_blank", then you know it isn't null or undefined, so:

var targ = jQuery(this).prop("target").toLowerCase();

var c = targ === "_blank" ? 1 : 0;

Or you could make it even shorter by coercing the boolean to a number:

var targ = jQuery(this).prop("target").toLowerCase();

var c = +(targ === "_blank");

These last two solutions are safe because .prop() will always return a string.

like image 164
the system Avatar answered Nov 02 '22 14:11

the system


  • Both null and undefined are "falsy" values, thus they can be checked like they were boolean values. Thus, there's no sense comparing to null and undefined except for certain situations where you need to know if they are such values.

  • when comparing, it's best to use strict comparison (like ===,!== and so on)

  • the && in a condition does not evaluate the following condition if the one preceeding it is "falsy".

  • You don't even need jQuery since this is your DOM object (presumably an <a>) and you are trying to get the target property:

In the end:

var c = (this.target && this.target.toLowerCase() === "_blank") ? 1 : 0;
like image 22
Joseph Avatar answered Nov 02 '22 12:11

Joseph