When requesting to view an array in the console (which is not part of the JavaScript specification), the console interprets it as a request to display only the array elements. This is how Google decided to implement the console, but it doesn't mean that there aren't other properties associated with the array.
An array is actually an object and possesses all the capabilities of an object. You can assign properties to it just like any other object since it technically is an object.
In addition, arrays have a unique property called .length
which automatically tracks the length of numeric properties assigned to it. This feature gives arrays their distinct characteristics and provides various methods for handling the sequential nature of arrays such as .push()
, .pop()
, and .slice()
. Plain objects do not have the special .length
property or those array-specific methods. Arrays may also utilize internal optimizations to improve efficiency when dealing with consecutive runs of numeric properties.
To iterate through array elements specifically, you can use:
for (var i = 0; i < arr.length; i++) {
// access arr[i] within this loop
}
or utilize .forEach():
arr.forEach(function(value, index, array) {
// utilize value and index within this function
})
Alternatively, you can iterate through all properties by using:
var props = Object.keys(arr);
for (var i = 0; i < props.length; i++) {
// access props[i] to retrieve the property
// and arr[props[i]] to get the corresponding value
}
or by implementing:
for (var prop in arr) {
if (arr.hasOwnProperty(prop)) {
// access arr[prop] within this loop
}
}