DEV Community

Discussion on: 1 line of code: How to check if an Array is empty

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan • Edited

I would prefer something like this:

const isEmptyArray = (arr) => {
  return Array.isArray(arr) && !arr.length;
}
Enter fullscreen mode Exit fullscreen mode

No need for a ternary since Array.isArray and the negation operator already return booleans.

Imo, it doesn't make sense to throw (edit: return) an error in this case since the function is just a predicate. So it should return true or false. Otherwise, the user has to wrap it in a try-catch.

I also don't recommend using braceless arrow functions; I've often found myself refactoring them so I can use a debugger/console log inside the function later on. It seems tempting to omit the braces at first, but there's no practical benefit in doing so.

Collapse
 
martinkr profile image
Martin Krause

Thank you for your extensive contribution.

I can understand you comments and see where ou are coming from. Let me explain why I use this code.

I was using the version you posted for some time but ran into the problem that it returns false if the argument is not an array. This lead to problems in the code relying on the return value.

I'm deliberately not throwing the error,so it's not necessary to wrap it in an try ... catch - you can decide how to handle the error by yourself.

Cheers!

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

It seems tempting to omit the braces at first, but there's no practical benefit in doing so

Readability; there's also no real downside (if you want to add a console.log, there's better ways to do it).

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

I disagree. I've run into this trap so many times myself and then still had to go back and add a console statement or debugger. Same issue with early-return statements that don't have braces, especially if you have multiple ones. It's useful to know when/if you've landed in a particular scope at all.

Some comments have been hidden by the post's author - find out more