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; }
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.
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) { ... }
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.
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")
I generally like the shorthand version:
if (!!wlocation) { window.location = wlocation; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With