Open In App

Are JavaScript arrays objects?

Last Updated : 08 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Yes, JavaScript arrays are actually specialized objects, with indexed keys and special properties. They have a length property and are technically instances of the Array constructor.

JavaScript
const a = [10, 20, 30];
console.log(typeof a);

Output
object

You can add non-integer properties to arrays, making them work partly like objects. However, this is usually discouraged for clarity.

JavaScript
let a = [1, 2, 3];

// Adding a property to array (NOT RECOMMEMDED IN PRACTICE)
a.name = "MyArray";

console.log(a.name);       

// Iterating through the array with `for...in`
// (NOT RECOMMENDED IN PRACTICE)
for (let key in a) {
  console.log(`${key}: ${a[key]}`);
}

// Despite adding an extra property, arr.length remains 3
// because only numeric indices count toward the length.
console.log(arr.length)

Output
MyArray
0: 1
1: 2
2: 3
name: MyArray

Why it is not recommended to treat arrays like normal objects and add properties?

Adding non-integer properties to arrays can lead to unexpected issues:

  • Arrays are typically used to store ordered lists, so adding properties may make code harder to understand.
  • Some iteration methods, like for...in, will include these properties, which might cause bugs.
  • Many array methods (like map, filter, and forEach) only work on elements with numeric indices, so the extra properties won’t be included in these operations.

In general, if you need additional properties, it’s better to use an object or another structure instead.




Next Article

Similar Reads