I was playing with instanceof in javascript and I stumbled upon the following.
Array instanceof Object
returns true
Object instanceof Array
returns false
What is the relationship between Array and Object here ?
Between the constructors, the relationship or prototype chain is:
Array -> Function.prototype -> Object.prototype
Object -> Function.prototype -> Object.prototype
The 1st is true because a constructor is a Function and functions are themselves Objects.
Array instanceof Function // true
Object instanceof Function // true
(function () {}) instanceof Object // true
You're testing the Array constructor. The Array constructor is a function used for creating arrays. So Array instanceof Function is true, and Array instanceof Object is true (since all JS objects inherit from the Object prototype. But since this is a constructor function, not an actual array Array instanceof Array is false.
Object is the Object constructor, which all objects inherit from. Since its still a function Object instanceof Function is true, as is Object instanceof Object.
None of that is what you're really meaning (I think) to test. We can test an actual array (rather than the constructor)
and get [] instanceof Array and [] instanceof Object to be true (while [] instanceof Function is false). This is because all arrays are arrays, all arrays are objects, but arrays are not functions.
we can also test an object and get
{} instanceof Object is true, but {} instanceof Array and {} instanceof Function are false.
The key things here
Array is a reference to a constructor function, not an actual array. Constructor functions are Functions, and all Functions are Objects.
An Actual Array is an Array, which means its an Object, but is not a Function.
Under the covers instanceof is looking up an objects "prototype chain" to find any constructors that it inherits from.
An array is an object, but an object is not an array. Object is a base class in Javascript, if it's not a primitive then it's an object, therefore arrays fall into that. But of course an object isn't necessarily an array.
Array instanceof Object, there are no arrays, so the statement "an array is an object," while true, does not actually apply.Array constructor, not an array instance.
instanceoftold youArrayandObjectare two constructor functions. The second thing is to understand howinstanceofworks. Related question: Why in JavaScript both “Object instanceof Function” and “Function instanceof Object” return true?Array instanceof Objectistruebecause functions are objects and every object hasObject.prototypein its prototype chain.