0

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?

2
  • 4
    [''] is NOT empty Commented Oct 18, 2022 at 6:46
  • Only undefined and null loosely equal(==) to null, try using if(!az[0]) as the condition. Commented Oct 18, 2022 at 6:50

3 Answers 3

1

use "" (empty string) instead of null.

example:

if(arr[0] == ""){
    console.log(1);
}else{
    console.log(2);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Though this answers the problem OP asked, BUT it's not an empty array check. it checks for a non-empty array if the first element is an empty string
Yes, you’re right. I just provided an example based on the code the OP shared.
0

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

Comments

0

This is how you check empty arrays

if(!az.length) {
   console.log("Empty array");
} else {
   console.log("Not an empty array");
}

4 Comments

Although Not Working
Why are you logging "empty array" in the second one as well?
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
@PaulGhiran sorry, I forgot to change the second log ^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.