Hunter
Hunter

Reputation: 357

JavaScript: in what sense are objects `{}` and arrays `[]` the same or different

I'm trying to understand the following output:

'use strict';
console.log(Object.getPrototypeOf([]));
// [] 
console.log(Object.getPrototypeOf(Array.prototype));
// {}
console.log(Object.getPrototypeOf([]) == Array.prototype);
// true
console.log(Object.getPrototypeOf([]) === Array.prototype);
// true
console.log([]=={});
// false
console.log([]==={});
// false

In particular, why are lines 6 and 8 evaluated to be true, whereas lines 10 and 12 are evaluated to be false.#

Edit: I made a stupid typo on lines 6 and 8, which I have now edited. This makes the question different. Apologies.

Upvotes: 0

Views: 98

Answers (3)

Lihai
Lihai

Reputation: 323

All prototypes in Javascript eventually inherit from the same object prototype. That's why if you will add a property to the object prototype, all the objects in your program will end up having this property. In lines 6 and 8 you are comparing Object.prototype to itself, which is equal.

However in lines 10 and 12, you are comparing 2 different objects, they may share the same prototype, but these are completely two different objects in memory.

Upvotes: 3

knittl
knittl

Reputation: 265211

[] will create a new array instance. Two instance are different from each other (you can modify them independently). The same holds for {}, it creates a new object instance.

All array instances share the same prototype instance (there is only a single array prototype instance). The prototype of an array prototype is an object.

They just happen to have the same string/JSON representation.

What you are basically doing in your second console.log example is: console.log(Object.getPrototypeOf(Object.getPrototypeOf([])))

The last two lines return false because you are comparing objects and arrays (which cannot be equal)

Upvotes: 1

RocketNuts
RocketNuts

Reputation: 11130

In lines 6 and 8, you are literally comparing two exact same expressions.

(X)===(X) is always1 true for any X, and in that case (X)==(X) is also automatically true (not always the other way round).

[] and {} are not the same, hence the false from line 10 and 12.

(1) assuming of course that X is a non-destructive or read-only expression, if X is something like (Y++) then this doesn't hold.

Upvotes: 2

Related Questions