B. Clay Shannon B. Clay Shannon - 7 months ago 10
Javascript Question

How can I check a value for null in jquery without getting an error?

I've got this code:

if (returneddata.daterangeparams.TimeUnitsFrom != null) {


...which throws this error (as seen in the Chrome Dev Tools console) when the value is, indeed, null:

Index:1031 Uncaught TypeError: Cannot read property 'TimeUnitsFrom' of null


So how can I check for null in a way that I can avoid the error?

Based on a suggestion here, I even tried this:

if (returneddata.daterangeparams.TimeUnitsFrom != null && variable !== undefined) {


...but I still get the same whinging from the guts of the browser.

Code in greater context:

function populatedaterangeprams(rptval, returneddata) {
var fromval = '';
var toval = '';
if (returneddata.daterangeparams.TimeUnitsFrom != null && returneddata.daterangeparams.TimeUnitsFrom !== undefined) {
fromval = returneddata.daterangeparams.TimeUnitsFrom;
}
if (returneddata.daterangeparams.TimeUnitsTo != null && returneddata.daterangeparams.TimeUnitsTo !== undefined) {
toval = returneddata.daterangeparams.TimeUnitsTo;
}

if (rptval === 1) {
// Produce Usage
$("#produsagefrom").val(fromval);
$("#produsageto").val(toval);
} else if (rptval === 2) {
. . .


So how can I safely check for null in javascript/jQuery?

UPDATE



As Phil Varg said, I needed to do this:

if (returneddata != null && returneddata.daterangeparams != null && returneddata.daterangeparams.TimeUnitsFrom != null) {
fromval = returneddata.daterangeparams.TimeUnitsFrom;
}
if (returneddata != null &&
returneddata.daterangeparams != null &&
returneddata.daterangeparams.TimeUnitsTo != null) {
toval = returneddata.daterangeparams.TimeUnitsTo;
}


...but that seems clunkier than a silicone-and-duct-tape job on the LHC. Isn't there a way to concisify this, where checking returneddata.daterangeparams.TimeUnitsTo for null would first check the first two subparticles of that?

Answer

the problem is that returneddata.daterangeparams is null. and youre calling TimeUnitsFrom on it. so you need to check that returndata is not null, and returndata.daterangeparams is not null, and returneddata.daterangeparams.TimeUnitsFrom is not null

Comments