DEV Community

Austin Baune
Austin Baune

Posted on

TypeOf Array is Gotcha!

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)

Collapse
 
secure_daily profile image
Artem

For me one of the recent things was sort() method of the Array object:

[3,100,20].sort() //outputs [ 100, 20, 3 ]

I had no idea it sorts them as string literals.

Collapse
 
qm3ster profile image
Mihail Malo

The other gotcha is that it mutates the source array, and then also returns it, unlike most Array.prototype methods.

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

I'm assuming that, once you realized the problem, you leveraged the Array object? That would be like:

const foo = {foo: 'bar'};
console.log(Array.isArray(foo));  // FALSE

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:

const foo = [3,2,1];
console.log(is.anObject(foo));  // FALSE

And the logic it uses under the covers is:

typeof value === 'object' && !Array.isArray(value) && value !== null

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:

const foo = '';
console.log(is.aPopulatedString(foo));  // FALSE
Collapse
 
qm3ster profile image
Mihail Malo

The objectness is also very obvious in the fact that [] is truthy, unlike "" .