Jeremy
Jeremy

Reputation: 973

jQuery / Javascript code check, if not undefined

Is this code good?

var wlocation = $(this).closest('.myclass').find('li a').attr('href');
if (wlocation.prop !== undefined) { window.location = wlocation; }

or should I do

var wlocation = $(this).closest('.myclass').find('li a').attr('href');
if (wlocation.prop !== "undefined") { window.location = wlocation; }

Upvotes: 40

Views: 127073

Answers (3)

Bruno
Bruno

Reputation: 6000

$.fn.attr(attributeName) returns the attribute value as string, or undefined when the attribute is not present.

Since "", and undefined are both falsy (evaluates to false when coerced to boolean) values in JavaScript, in this case I would write the check as below:

if (wlocation) { ... }

Upvotes: 4

Diego
Diego

Reputation: 16714

I like this:

if (wlocation !== undefined)

But if you prefer the second way wouldn't be as you posted. It would be:

if (typeof wlocation  !== "undefined")

Upvotes: 104

jeremy
jeremy

Reputation: 4314

I generally like the shorthand version:

if (!!wlocation) { window.location = wlocation; }

Upvotes: 14

Related Questions