Reputation: 755
I am getting data from ajax call like
[{"_id":{"$oid":"5bd00e99d2ccda119c0032da"},"AllotmentsDetails":null}]
I am comparing it for null value like
var allotmentDetailsArray = data[0]['AllotmentsDetails'];
if (allotmentDetailsArray.length == 0 || allotmentDetailsArray == null)
{
////
}
It is not going in if condition... Please help !!!
Upvotes: 1
Views: 945
Reputation: 99
First you have to check null or not null. if its not null means then check length.
Please try it.
//Ex:1
var data= [{"_id":{"$oid":"5bd00e99d2ccda119c0032da"},"AllotmentsDetails":null}];
var allotmentDetailsArray = data[0]['AllotmentsDetails'];
if (allotmentDetailsArray == null)
{
alert(allotmentDetailsArray);
}
else if(allotmentDetailsArray.length == 0)
{
alert(allotmentDetailsArray.length);
}
//or
if (allotmentDetailsArray == null ||allotmentDetailsArray.length == 0 )
{
alert(allotmentDetailsArray);
}
//Ex:2
var data= [{"_id":{"$oid":"5bd00e99d2ccda119c0032da"},"AllotmentsDetails":""}];
allotmentDetailsArray = data[0]['AllotmentsDetails'];
if (allotmentDetailsArray == null)
{
alert(allotmentDetailsArray);
}
else if(allotmentDetailsArray.length == 0)
{
alert(allotmentDetailsArray.length);
}
Upvotes: 1
Reputation: 2109
You cannot check length of a null value. However you can check null value and array length with this code.
if (!allotmentDetailsArray) {
// null check here. you cannot check array length here since it's a null value
} else {
// if you want to check array length
if (allotmentDetailsArray.length === 0 ) {
// check here
}
}
Upvotes: 1
Reputation: 32145
You have to check against null
before trying to access the object
, in your if
block you are trying to call .length
on a null
object.
You can do it like this:
if (!allotmentDetailsArray || allotmentDetailsArray.length == 0)
{
////
}
Where !allotmentDetailsArray
is a shortened expression for allotmentDetailsArray == null
which checks that allotmentDetailsArray
is undefined
or null
.
So here the second part of the if
block is only checked when allotmentDetailsArray
is not null
.
Upvotes: 3
Reputation: 25
You can just check the type:
var allotmentDetailsArray = data[0]['AllotmentsDetails'];
if (typeof allotmentDetailsArray !== "undefined")
{
// Var is not null
}
Upvotes: 0
Reputation: 527
You have to check null first then check for length
if (allotmentDetailsArray == null || allotmentDetailsArray.length == 0)
{
////
}
Upvotes: 2