JavaScript Shenanigans: Empty Arrays

I yelled at the computer this week about empty arrays in JavaScript. Find out why.

Introduction

JavaScript, like every language, is weird in it’s own ways. As I continue diving in, I am starting to realize the depths of the silliness.

So the other day, I wrote some logic for something using pure JavaScript. It looked a little like this.

Code with issues

This would eventually be used to create an array of objects with months and total users for that month. I wanted to do this by creating an array, looping through data, and checking if the array was empty. Add the first empty object to the array. If it was not empty, run the logic for the next object in the array.

Pretty simple, I’ve done it similarly in Python many times. So I couldn’t understand why nothing was working.

Come to find out, JavasScript like’s to do things a certain way.

The initiated amongst you already noted this, but for the rest of us draw your attention to line seven for the issue.

Highlighted issues from the sample code.

JavaScript will evaluate empty arrays (and objects) as truthy or True in a boolean context.

What? Why?

It made no sense to me why this was happening. It’s an empty array. In Python, when using a boolean operation, arrays utilize the __bool__ or __len__ dunder function, which, if the array is empty, returns a 0. Which evaluates to False. The above is common practice for Python code.

Not in JavaScript.

This might be just me getting glasses for the first time and realizing that leaves on trees are not weird green blobs but have shapes. I don’t know. But I say again; Why?

I mean... why?

Why?

They (kind of but not really) tell you right in the MDN docs. And to quote them:

All values are truthy unless they are defined as falsy. That is, all values are truthy except False, 0, -0, 0n, "", null, undefined, and NaN.

So JavaScript has some magic going on that treats even empty arrays as objects and evaluates them as True. Type coercion is that magic.

Type coercion is the process JavaScript uses when making comparisons. So, for example, if we have '1' == 1, the JavaScript will compiler will coerce the number type 1 into a string and returns True. You can force type checking by doing this '1' === 1, which will return False. I learned that early, although I did not realize it was through the same process that would trip me up now.

JavaScript coerces the empty array to be True in my code, and my logic doesn’t work.

This is not a problem, just an odd quirk. I avoided this by checking the length directly—no big deal.

Corrected code

And now we’re good. I hope this helps someone new to the language, and I’m sure I’ll write about its quirkiness in the future.

-George