Why typeof Returns 'Object' for JavaScript Arrays
JavaScript
November 26, 2023
JavaScript Arrays as Objects: The Mystery Behind typeof
In JavaScript, one of the most common surprises developers encounter is when they use the typeof
operator on an array and it returns "object"
instead of "array"
. This behavior often confuses beginners because arrays and objects seem like different structures. So, why does JavaScript treat arrays as objects when using typeof
? Let’s dive into the reasoning behind this and clarify what’s happening under the hood.
Understanding typeof
in JavaScript
The typeof
operator in JavaScript is used to determine the type of a given operand. It returns one of the following string values:
"number"
"string"
"boolean"
"undefined"
"object"
"function"
"symbol"
(introduced in ES6)"bigint"
(introduced in ES2020)
When you run typeof []
, which checks the type of an array, the result is "object"
. While this may seem counterintuitive, it actually makes sense when we explore how JavaScript structures work.
Arrays in JavaScript Are Objects
In JavaScript, arrays are specialized objects. In fact, almost everything in JavaScript is an object. An object in JavaScript is essentially a collection of key-value pairs, and arrays are just a specific kind of object designed to store ordered collections of data, indexed numerically.
Let's explore why arrays are considered objects:
- Arrays Inherit from the Object Prototype: Arrays in JavaScript are objects at their core, inheriting properties and methods from the Object prototype. The array itself has its own prototype, which provides additional functionality like
.push()
,.pop()
, and.length
, but fundamentally, it’s an object.
Example:
let arr = [1, 2, 3];
console.log(typeof arr); // "object"
console.log(arr instanceof Object); // true
- Arrays Use Numeric Indices as Keys: In JavaScript, arrays use numeric indices as keys, but internally, they are still treated as key-value pairs like regular objects. Each element in an array is a property of that object with a numeric key.
Example:
let arr = [10, 20, 30];
console.log(arr[0]); // 10
console.log(arr['0']); // 10, works because arrays use string-based property keys like objects
In this sense, arrays are essentially objects with numeric keys and extra functionality for handling collections of data.
Why typeof
Returns "object"
for Arrays?
When JavaScript was initially created, arrays were designed as a type of object. The typeof
operator was implemented to distinguish between primitives like numbers, strings, and booleans versus complex data types like objects. Since arrays were considered objects from the beginning, typeof
was designed to return "object"
for arrays as well. Unfortunately, this behavior is part of the language specification and can't be changed without breaking backward compatibility.
Here’s a simplified breakdown of why typeof [] === "object"
:
- Arrays are a specialized type of object.
- JavaScript's
typeof
operator has been programmed to return"object"
for all object types, including arrays. - The
typeof
operator is relatively limited in scope and does not differentiate between regular objects and arrays.
How to Properly Check if Something is an Array
Since typeof
doesn't return "array"
, developers need a more reliable way to check if a value is an array. JavaScript provides a built-in method to accurately check this: Array.isArray()
.
let arr = [1, 2, 3];
console.log(Array.isArray(arr)); // true
let obj = { a: 1, b: 2 };
console.log(Array.isArray(obj)); // false
The Array.isArray()
method was introduced in ECMAScript 5 (ES5) to solve the problem of accurately determining whether a value is an array. It’s the recommended way to check for arrays in modern JavaScript.
A Note on instanceof
Another way to check if a value is an array is using the instanceof
operator. This checks whether an object is an instance of a particular constructor.
let arr = [1, 2, 3];
console.log(arr instanceof Array); // true
While instanceof
works for checking arrays, it can fail in scenarios where arrays come from different execution contexts, like iframes, because each iframe has its own global context and thus its own Array
constructor.
Conclusion
In summary, the reason typeof
returns "object"
for arrays is due to the way JavaScript was designed. Arrays are a specific type of object, and they inherit from the object prototype. While typeof
may not return "array"
, JavaScript provides other, more accurate methods—like Array.isArray()
—to identify arrays.
Though this behavior might seem quirky at first, understanding that arrays are objects with specialized behavior will help you avoid confusion and use the right tools when working with JavaScript data structures.
By knowing how typeof
works and understanding JavaScript's object model, you can make better decisions when working with arrays and other data types. Keep this in mind as you continue your journey with JavaScript, and always use Array.isArray()
when you need to check if a value is an array!
Also read: 3 Ways to Check if a Function is Defined in JavaScript
Also read: How to Check if a Variable or Constant is Defined in JavaScript
Is this article helpful?
Admin
About Author
A full stack web developer specializing in frontend and backend web technologies. With a wealth of experience in building dynamic and robust web applications, he brings expertise and insights to his articles, providing valuable guidance and best practices for fellow developers. Stay tuned for more useful content.
Share the good stuff on social media and earn appreciation.