Today I was fooled by a common gotcha in Javascript where the type of an Array is an Object. Duh. I know Arrays are just objects, but just goes to show that gotchas can get anyone.
In an attempt to help my pride please share some other common gotchas (in Javascript or any language) that you've come across that maybe tripped you up for a bit; even if it hurts inside to admit :).
Top comments (4)
I'm assuming that, once you realized the problem, you leveraged the
Array
object? That would be like:It was precisely these kinda "gotchas" that led me to write my own little utility library that I now use all over my code. I wrote an article about it here:
dev.to/bytebodger/javascript-type-...
It gives me one central location where I can do Boolean checks as to whether a given variable meets a given condition.
For example, it uses this to determine whether something is an object:
And the logic it uses under the covers is:
Because, as you've pointed out, the
typeof
an array is...object
. Also,typeof
null is...object
.With a utility like this, you can also write more robust checks. For example, when you are writing a function that expects a string, you often don't want the parameter to be an empty string. That's why I have checks such for that too. I use it like this:
For me one of the recent things was sort() method of the Array object:
I had no idea it sorts them as string literals.
The other gotcha is that it mutates the source array, and then also returns it, unlike most
Array.prototype
methods.The objectness is also very obvious in the fact that
[]
is truthy, unlike""
.