DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 967,911 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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 on

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 Author

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
 
jfbrennan profile image
Jordan Brennan • Edited on

Why wouldn't you just check if length is falsy wherever you need to know if it's empty? If there's a risk the array may not exist, then check length using optional chaining, e.g. safely checks if this thing is empty myArr?.length ? 'something' : 'nothing'.

Collapse
 
martinkr profile image
martin krause Author

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 Author

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
 
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 Author

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

Collapse
 
kuch311 profile image
Kuch311

Following

Collapse
 
jancizmar profile image
Jan Cizmar

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

Collapse
 
lukeshiru profile image
Luke Shiru • Edited on

I was about to say the same. This function is checking if the array is empty but also if it's an array in the first place. Ideally those two things should be in different functions, so isEmptyArray could be just:

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

And you could even use JSDocs or TS to warn the dev when is using this with something that could not be an array.

Collapse
 
code913 profile image
Info Comment hidden by post author - thread only accessible via permalink
code913

const isEmptyArray = arr => !!arr.length

khaby lame moment
who needs a package for that

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

Classic DEV Post from 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!