Quantcast
Channel: Why do empty JavaScript arrays evaluate to true in conditional structures? - Stack Overflow
Viewing all articles
Browse latest Browse all 8

Answer by bvdb for Why do empty JavaScript arrays evaluate to true in conditional structures?

$
0
0

While [] equals false, it evaluates to true.

yes, this sounds bad or at least a bit confusing. Take a look at this:

const arr = [];if (arr) console.log("[] is truethy");if (arr == false) console.log("however, [] == false");

In practice, if you want to check if something is empty,then check the length. (The ?. operator makes sure that also null is covered.)

const arr = []; // or null;if (!arr?.length) console.log("empty or null")

Viewing all articles
Browse latest Browse all 8

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>