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.
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
__len__ dunder function, which, if the array is empty, returns a
0. Which evaluates to
False. The above is common practice for Python code.
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?
All values are truthy unless they are defined as falsy. That is, all values are truthy except
True. Type coercion is that magic.
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.
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.
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.