DEV Community

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

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.

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