TypeOf array = “object”. Why though?

Answering the “weirds” parts of JavScript. Let’s find out why typeof array = “object”.

const anArray = [1,2,3,4]
console.log(typeof anArray) // output: "object"

Recently I found that typeof [] = 'object' when I was doing some variable type comparison and I was surprised. Why the outcome wasn’t ‘array’ instead of ‘object’? I believe some of us will start to think JavaScript is funny. That’s because we do not know how JavaScript really works under the hood.

How does JavaScript define array?

Long story short, JavaScript is a prototype-based language. It defines all objects as dictionaries, with string keys mapping to property attributes. Arrays are defined as a special case of objects (by the author). What makes it a little special is it has special handling of array indices (index) and it has the length property which defines the length of the array.

const anArray = [1,2,3,4]
anArray.length // 4
anArray[1] // 2

JavaScript defines arrays similarly to objects. You can imagine the indices and length are the property attributes of the array (which is technically an object). Up to this point, I don’t know whether should I be laughing or crying. But anyways, let’s continue.

If I can’t use typeof, what should I use?

Glad to know that JavaScript has a ready made array method (Array.isArray) for us (developer) to ease our burden. Instead of attempting to check the length of the variable.

Use Array.isArray method

const anArray = [1,2,3,4]
Array.isArray(anArray) // true

Bonus

Now this actually is not related to the main topic and I just felt like sharing it here.

const objectA = {}
objectA.name = "Alex"
objectA.profile.age = 10 // error thrown here. Why?

As you can see from the example code above, we would always get an error (Uncaught TypeError: Cannot set properties of undefined (setting 'age')) when trying to create nested object in such a way. Have you ever wondered why a nested object cannot be created thru this method? The answer to that is the engine does not know profile property is an object. In order for the engine to know/process, it needs to know the profile property has a shape of an object. Since it was not define, the engine do not know what it is which is why you will see error: cannot set properties of undefined. profile is the undefined.

Resources