A Weird Way To Check If A JavaScript Object Is An Array

There are several ways to check if an array in JavaScript is actually an object. Some ways are very clean but some can be said “weird”.

Let’s take it step by step

Object.create

var arr = ['a', 'b'];

var arrChild = Object.create(arr);

in the above code snippet arrChild will have its prototype linked to arr. And with the prototype linkage, even the length will be used from prototype chain. This is confirmed by following code snippet.

hasOwnProperty

arrChild.hasOwnProperty('length')
// false

arr.hasOwnProperty('length')
// true

Unique thing about arrays (along with several other unique things) is that as soon as we update the arrChild, the length property will be automatically updated and shadowed by the arrChild. Which means length will now exist directly on the arrChild. This is confirmed by following snippet.

arrChild.push('c');

arrChild.hasOwnProperty('length');
// true

Putting everything together

When we think about the whole process, we realize that arrays have a unique behaviour by which they automatically update the length property. But the length property would not have automatically updated if we had performed these operations on an object that is not an array.

Side Note 1:

You may not often encounter this in your code, but it’s fun to explore some of JavaScript’s quirks. They might not seem so strange when you dive deeper into how they actually operate behind the scenes though.

Complete code Snippet

var arr = ['a', 'b'];

var arrChild = Object.create(arr);

arrChild.hasOwnProperty('length')
// false

arr.hasOwnProperty('length')
// true

arrChild.push('c');

arrChild.hasOwnProperty('length');
// true

Side Note 2:

When we create an array with Object.create, the indices from parent array are directly accessible on the child array.

var arr = ['a', 'b'];

var arrChild = Object.create(arr);

arrChild.length;
// 2

arrChild[0];
// 'a'

arrChild.push('c')
arrChild.length
// 3

Found any problem in this article? Email me at wtf@abhishek.wtf


Leave a Reply

Your email address will not be published. Required fields are marked *