Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; } 
like image 265
Jeremy Avatar asked Nov 28 '12 14:11

Jeremy


People also ask

How do I check if JavaScript is not undefined?

In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.

How do you check does not equal undefined in jQuery?

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) { ... }

Is not defined check jQuery?

You may experience the “jQuery is not defined error” when jQuery is included but not loaded. Make sure that it's loaded by finding the script source and pasting the URL in a new browser or tab. The snippet of text you should look for to find the URL to test.


2 Answers

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") 
like image 187
Diego Avatar answered Sep 21 '22 19:09

Diego


I generally like the shorthand version:

if (!!wlocation) { window.location = wlocation; } 
like image 36
jeremy Avatar answered Sep 23 '22 19:09

jeremy