Uliana Pavelko
Uliana Pavelko

Reputation: 2952

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?

Upvotes: 4

Views: 10957

Answers (3)

Ben Racicot
Ben Racicot

Reputation: 5980

If you have an empty array, that is an array with 0 length,

single negation with ! returns a misleading boolean.

arr = []

!arr.length // true - because `0` is `false`, `!` negates `false` to `true`

// double negate it for clear boolean
console.log(!!arr?.length, arr?.length); // false 0

Truthy example

arr = ['','','']

// array with values 
console.log(!!arr?.length, arr?.length); // true 3

Make sure to check if .length exists with optional chain ?

if (!!arr?.length) console.log(!!arr?.length);

Now you can reliably use .length as a boolean to check for empty arrays.

Note: Double negation has caveats like ESLint's no-extra-boolean-cast

Upvotes: 0

gobaldia
gobaldia

Reputation: 420

This is because length function returns a Number and when you use Number as condition, 0 and NaN are evaluated as false (in other case is evaluated as true).

Upvotes: 0

cнŝdk
cнŝdk

Reputation: 32145

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.

Upvotes: 3

Related Questions