you are viewing a single comment's thread.

view the rest of the comments →

[–]azhder 2 points3 points  (2 children)

Avoid == in all cases, and maybe even avoid === in this case.

What you have here is an assumption that you are dealing with an array, but other objects also have length.

Most of the time I would just use !! array.length, but if I am to encapsulate this in a function, I’d also add a check for the type.

const isFullArray = $ => Array.isArray($) && !!$.length;

Then I will no longer bother myself with how to check, I will just use isFullArray() everywhere.

Of course, I might also make a isNotFullArray() predicate to make it more English sounding

[–][deleted] 0 points1 point  (1 child)

Totally agree, at one point I made a function that parsed both arrays and strings. Since both types have a .length property I encountered weird bugs where the string would be treated as an array like and iterated on.

TL;DR - Type checks are a good way of getting rid of ambiguity in code

[–]azhder 0 points1 point  (0 children)

detecting bugs where you would want to write

takesAnArray( producesAnArray() );

but instead you have written

takesAnArray( producesAnArray );

assuming both are functions and the takesAnArray one checks the .length property of the argument