jQuery / Javascript code check, if not undefined

Jeremy picture Jeremy · Nov 28, 2012 · Viewed 105.9k times · Source

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; }

Answer

Diego picture Diego · Nov 28, 2012

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")