instanceof
is a query operator that tests an object instance against a potential constructor.
Consider,
const a = []
console.log(a.constructor) // Array
console.log(a instanceof Array) // true
We already know that arrays are objects. What the above identifies for us is its custom object constructor. Objects inherit from their parent constructor’s prototype. Array objects inherit from, Array.prototype
.
console.log(a.constructor.prototype)
// object containing Array methods
In the earlier post we showed evidence that Array is first off, an object, so must inherit from Object.prototype
, as ALL objects do, regardless their parent constructor. Inheritance is distinctly tied to the prototype chain which leads up through their constructor’s prototype all the way up to Object.prototype and thence to, null, the very top of the chain.
Because arrays have a set index that can never be altered it necessitates immutability of the keys so they cannot be messed with. We can shift things around, pop and push but the order of the keys never changes, only the values associated with them. So the interesting thing here is that the association of key and value is mutable, and not fixed the same way object key and value pairs are. In an ordinary object, when we move a key, its value goes with it. Not so with arrays. We cannot move the keys.
When we move a value, its key will change, depending its position relative to the index. The index of every element in the array may change. When we remove a value, the index is updated.
Only the system can manipulate the index as it updates after any changes, such as insertion (splice), pushing and unshifting, popping and shifting, and sorting. The values move around, but the index stays ordered through all of it.
Objects cannot have duplicate keys. The system makes sure of this. It is partly due to arrays, but it would never make sense to have duplicate keys, and I’m sure you can see why.
None of the above is important to know, though it is always nice to partly understand what is going on under the hood. The why of it is kind of moot. We might never need to know the inner workings while we learn and gain proficiency using the language. It’s more important we know how to implement the various array methods and be able to predict the outcome than it is to know what sort algorithm JS uses. Some things we just accept as promised.
Kind of rambling on, here. Best wait for more questions before muddying the waters any further.