The thing about Arrays that are made with the core js Array constructor, or literal syntax, is that they are a special kind of object in which the objects constructor name is Array. This also means there there are a bunch of array prototype methods that can be used with that instance of Array also. However there are also array like objects in addition to Arrays. What this means is that if any object contains a length property that has a value that is a number from 0 to the max safe integer, then it is “Array like” and can be used with methods that act on arrays. If you are confused then in this post I will try to help reduce some of this confusion, and of course it will be best for you to just work out some examples of your own when it comes to learning by doing.
You can gain a better sense of what is going on by checking out what the constructor is of an Object.
Any object created with the Array literal notation, like in the above example, will result in an object that is an instance of Array, and therefore has Array methods like splice, slice, and join in it’s prototype.
It is possible to make just a plain old object with the object literal notation, and call Array methods on it using call. One way to do so would be to just create a plain object like always, but make some public keys that are numbers rather than named. The next step would be to add a length property that will be the max number of elements for the array. I now have an object that is not really an array, but it is an array like object that is formated like one. So then I can use the object with an array prototype method by calling the call method of the array prototype method that i would like to use with such an object.
An example of an Array like Object that is not an Array is the arguments object in functions. Every time a function is called there is an arguments object that is Array like in the sense that each of the arguments that you pass to the function is in it, in a fashion where the first argument is in a property called ‘0’, and the second argument is in a property called ‘1’, and so forth. In addition it even has a length property just like an Array, but it is not.
Say you just have some simple paragraph elements.
Again to some extent you can call Array methods on them, as long as the are read only methods, methods such as splice will cause an error, you need to use appropriate DOM manipulation methods to edit HTML.
Because Arrays are objects you can treat them like so. We have covered some examples of how you can treat Plain Objects, or any Object that is Array like, like an Array. How about treating an Array like an Object by adding some named keys to the object though.