All arrays are objects, but not all objects are arrays


#1

JavaScript has ordered collections (arrays) as well as dictionaries (objects). Technically, arrays are objects, but if you’re reading this post for any other reason than to correct my probably numerous mistakes, you would do best to pretend that this isn’t true, and treat objects and arrays as completely different beasts.

For example, it makes perfect sense to iterate over the properties of objects using for..in loops, but it’s a bad idea to do that over an array. It’s slow, it delivers unwanted junk when libraries have modified class prototypes, and it’s not guaranteed to give you things in order. A better way:

let nitems = ar.length;
for (let i = 0; i < nitems; i++) {
  doSomething(ar[i]);
}

Often when retrieving data from external sources (such as Firebase) you will be receiving objects when you are expecting arrays. This will bite you when trying to use Array methods and give cryptic errors about differs that support Object when you are using the data to back directives expecting arrays, such as ngFor.

There are methods that return arrays of either keys or values of an object: Object.keys and Object.values (not universally supported, but polyfills available).


What s wrong about arrays and objects?
Some stuff are not found, like filter()
Associative array Ionic2
@Input variable undefined
How to access an array from a json file
Property 'length' does not exist on type '{}'
JSON array displaying issue