[javascript] 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; }

This question is related to javascript jquery undefined

The answer is


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

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

I generally like the shorthand version:

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to undefined

Checking for Undefined In React Raw_Input() Is Not Defined How to resolve TypeError: Cannot convert undefined or null to object "undefined" function declared in another file? Passing Variable through JavaScript from one html page to another page Javascript - removing undefined fields from an object PHP How to fix Notice: Undefined variable: Undefined Symbols for architecture x86_64: Compiling problems Undefined or null for AngularJS PHP Notice: Undefined offset: 1 with array when reading data