A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/are-javascript-arrays-objects/ below:

Are JavaScript arrays objects? - GeeksforGeeks

Are JavaScript arrays objects?

Last Updated : 08 Nov, 2024

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);

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:

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



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4