Home > Net >  Checking first item of array in Javascript Goes Wrong
Checking first item of array in Javascript Goes Wrong

Time:10-18

I have an empty array named az and when I console.log(az), it returns this:

['']

Now I want to check that if az variable returns this [''] value, go to first condition, otherwise goto 2nd condition:

if(az[0] == null){
    console.log(1);
}else{
    console.log(2);
}

So when I run the if..else, I get 2 meaning that az[0] is not set to null

So what's going wrong here?

How can I properly if the variable az is set to null array (['']) properly?

CodePudding user response:

use "" (empty string) instead of null.

example:

if(arr[0] == ""){
    console.log(1);
}else{
    console.log(2);
}

CodePudding user response:

What I understood is, you want to print 1 if the list is empty, 2 if the list is not. For that you can do the following

if(az.length == 0)
{
   console.log(1);
}
else
{
   console.log(2);
}

Hope this helps

CodePudding user response:

This is how you check empty arrays

if(!az.length) {
   console.log("Empty array");
} else {
   console.log("Empty array");
}
  • Related