The weird quirk of JavaScript arrays (that you should never use)

by Adam Davis

Table of contents:

If you’ve done any type validation in JavaScript, you’ve probably noticed that arrays don’t have their own type.

typeof [] === 'array';
// false

typeof [];
// 'object'

To check whether a variable is an array, you’d have to use Array.isArray:

Array.isArray([]);
// true

But why don’t arrays have their own type? What are the implications of arrays actually being objects?

Arrays are just objects

In JavaScript, arrays are just special objects that use numerical keys and have their own methods.

Because of this, you can use methods from the Object class on arrays.

let a = [1, 2, 3];

Object.keys(a);
// [ '0', '1', '2' ]

Object.values(a);
// [ 1, 2, 3 ]

As a result, there’s also no limitations for the types of values you can store in an array. Other languages, like Java, might require you to only store values of the same type.

But since objects can store values of any type and JavaScript arrays are objects, there is no such limitation.

let b = [1, 'hello world', false, {}, []];

If you want to limit arrays to specific types, you can do so in TypeScript.

// Creates a string array
let stringArr: string[] = [];

// Creates an array that can hold strings or numbers
let stringOrNumberArr: (string | number)[] = [];

Keep in mind, however, that TypeScript only performs type safety a compile time, not runtime.

Here’s where things get a little weird

From the above example, we know that passing an array into Object.keys will give us the indices.

However, the keys that can exist on an array are not limited to non-negative integers.

let array = [];
array.push(1);

array;
// [ 1 ]

array.hello = 'world';

array;
// [ 1, hello: 'world' ]

Object.keys(array);
// [ '0', 'hello' ]

That’s right, JavaScript lets you add any valid object key to an array as well.

Luckily this doesn’t seem to break any other array functionality, such as the length property, but it can feel strange to store data this way.

array.length;
// 1

Please don’t actually use this

Just because you can do something, doesn’t mean you should.

JavaScript offers quite a bit of freedom compared to many other programming languages, but I would consider assigning additional properties to an array as an abuse of that freedom.

If anyone (including yourself) has to work with your code in the future, having a variable that acts as both an array and an object will hurt the code’s readability and maintainability.

What do you think?

Should this feature be left untouched or is there a practical use case that I’m unaware of? Let me know in the comments or on twitter.

Adam Davis

Share this post: