DEV Community

Cover image for 1 line of code: How to check if an Array is empty
Martin Krause
Martin Krause

Posted on • Updated on

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

const isEmptyArray = ({ length }) => length === 0;
Enter fullscreen mode Exit fullscreen mode

Assumes that the given argument is an Array and checks if it has entries.

Returns:

  • a boolean false if the array is not empty
  • a boolean true if the array is empty

The repository & npm package

You can find the all the utility functions from this series at github.com/martinkr/onelinecode
The library is also published to npm as @onelinecode for your convenience.

The code and the npm package will be updated every time I publish a new article.


Follow me on Twitter: @martinkr and consider to buy me a coffee

Photo by zoo_monkey on Unsplash


Top comments (18)

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.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

Because 0 is falsey, it's very important to remember that.

I would try this slightly shorter question, "is length of 0 not not falsey?"

const isEmptyArray = ({ length }) => !!length
Enter fullscreen mode Exit fullscreen mode

But here you can see the problem with the entire concept, if length is already falsey or truthy and length can be infinitly truthy or infinitly falsey, why even cast to a Boolean?

I would even go as far as to say that a Boolean is not actually useful in most cases as information is lost 🙂, know your trutheys from your falseys and you won't have to overerly defend your code. Typescript helps too 😂

Collapse
 
humansprout profile image
Erik Waters

IMO the utility of this function depends on how you interpret an array being "empty": if you pass an array of empty items the result may not be what the user expects

let arr = Array(2) // [ <2 empty items> ]
isEmptyArray(arr) // false
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lizy0329 profile image
lizy0329

lodash not be user expects too

const arr = Array(2)
_.isEmpty(arr);
=>
false

Collapse
 
martinkr profile image
Martin Krause

Thank you all for your contributions.

I closely followed the discussions and took some valuable insights for this and the upcoming code snippets.

For all the functions in this series we will stick to certain assumptions:

  • as long as it's javascript, we assume the user provides valid input. No type checking or other verifications.
    E.g.: No more checking if it's actually an array

  • keep the functions as simple as possible and reduce the functionality to a core. E.g.: empty items are still items, if necessary clean the array before passing it to the function.

I adjusted the code to the function LUKESHIRU suggested.

It seems to be the simplest form and passes all my test cases (given the assumptions).

Thanks you again and looking forward to your contributions to the upcoming articles.

Cheers!

Collapse
 
hnicolas profile image
Nicolas Hervé

Returning an error is not a best practice, your function should thow an error instead with a message when possible.

Collapse
 
martinkr profile image
Martin Krause

Thank you for your comment.

This being part of a more "universal library" approach, I decided not to throw an error with an error message.
The purpose of this one liner is to check if the given argument is an emtpy array, How you handle an error is out of scope. Throwing an error would force a try ... catch block, returning the error let's you decide how to handle (or ignore) the issue.
The same goes for the error message. I could be a status code or a text message, there are different preferences which should fit into your complete application - so again, check for the error and proceed to your liking.

I hope you can see my rationale behind the code.

Cheers!

Collapse
 
hnicolas profile image
Nicolas Hervé

A "universal library" should respect language best practices. There is a standard way to deal with errors in javascript and you just introduce a new solution that is really questionable in my opinion.

You say throwing an error would force the use of a try catch block but your solution introduce the need to check the result too.
One big problem is that Error is a truthy value so that is error prone for the caller of the function :

if(isEmptyArray({})) {
  // oups its not an empty array
}
Enter fullscreen mode Exit fullscreen mode

It is a bad practice to have a function that can return different types in js (boolean | Error) and having the caller to check the return type. If you really need to, you could use a tuple or an object that the caller can deconstruct.

Collapse
 
kuch311 profile image
Kuch311

Following

Collapse
 
joaolss profile image
João Lucas Silva

Why use the not operator (!) when you can simply invert the ternary? For one use this is negligible, but it can sum up to hurt performance, and also makes the code less readable

Collapse
 
martinkr profile image
Martin Krause

You are completely right - I adjusted the code.
Thank you!

Collapse
 
jancizmar profile image
Jan Cizmar

Hmm hmm, then you're doing more then you describe in the title...

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