Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Script: Array.length expression evaluate to boolean

How to check array length, if I need the expression to evaluate to boolean value as a result? For example:

var myArray = [];
if(!myArray.length){
  return;
}

Or:

vr myArray = [];
if(myArray.length == 0){
  return;
}

Both of the examples work, however I’d like to understand what is the difference?

like image 898
Uliana Pavelko Avatar asked Aug 30 '25 18:08

Uliana Pavelko


1 Answers

Here !myArray.length will return true in two cases:

  • If myArray.length===0 because 0 is a falsy value, so !0 will return true.
  • If myArray.length is undefined, in other words myArray is not an array so it doesn't have the length property, where undefined is falsy value too.

And the first one explains why both !myArray.length and myArray.length==0 are equivalent in your case.

like image 151
cнŝdk Avatar answered Sep 02 '25 07:09

cнŝdk