yannick1976
yannick1976

Reputation: 11585

In Javascript, is it guaranteed that {} !== {}?

EDIT: my question is different from the one you're linking to. Specifically, it doesn't say whether objects can be reused by the JS virtual machine.

In Javascript, is it guaranteed that two objects created successively (and of course not by assigning one to another) have a different reference?

Consider the following snippet:

let a = {};
let b = {}; // b can be created at any time after a is created
let areEqual = a === b; // comparison can be done at any time after b is created

Is it guaranteed that areEqual is false? That some processor optimization won't make b re-use a's reference?

Upvotes: 3

Views: 137

Answers (2)

John Ellmore
John Ellmore

Reputation: 2229

Per the ECMAScript 2018 spec, newly-created objects MUST have different underlying references.

Creating an object with the curly braces syntax (let x = {}) uses the object literal syntax to create an object. Per the spec (section 12.2.6.7):

ObjectLiteral : { }

  1. Return ObjectCreate(%ObjectPrototype%).

Looking up ObjectCreate in section 9.1.12, we see that ObjectCreate instantiates a new object instance:

  1. If internalSlotsList is not present, set internalSlotsList to a new empty List.
  2. Let obj be a newly created object with an internal slot for each name in internalSlotsList.

Most other common methods of creating an object (Object.create(), etc.) also use the ObjectCreate definition in the spec, so they'll behave the same way.

Thus newly created object literals are not allowed to share references under the hood.

Upvotes: 3

joshrathke
joshrathke

Reputation: 7774

Yes! Triple Equals is a combination of Value & Type. When you compare non-primitive variables in javascript what you are really comparing is their reference id. In other words, in your example a will never equal b, nor will it with any amount of processor optimization.

Upvotes: 5

Related Questions