3

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?

yannick1976
  • 10,171
  • 2
  • 19
  • 27
  • 1
    This is an opinionated answer, but YES, it is guaranteed that the equality will be false. Here are my reasons. 1. Doing an optimization would break code (an example would be redux IIRC). And the ROI of doing something that will be less. 2. An optimization like that would encourage bad practices. So I think no one will do something like that. Even if someone does, it would not become main stream. – Pubudu Dodangoda Aug 21 '18 at 01:33
  • 3
    This shouldn't be closed; this part of the question isn't covered in the supposed dupe: `Is it gauranteed...that some processor optimization won't make b re-use a's reference?` – John Ellmore Aug 21 '18 at 01:35
  • Thanks @JohnEllmore, indeed I'm mostly concerned about whether existing objects could be reused. – yannick1976 Aug 21 '18 at 01:36

2 Answers2

5

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.

joshrathke
  • 7,564
  • 7
  • 23
  • 38
  • 1
    The compiler can never make `b` use `a`'s reference because either or both `a` and `b` may be modified later; if the compiler "optimized" by setting both references to the same instance, **both** objects would appear to have been modified. – Timshel Aug 21 '18 at 01:45
3

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.

John Ellmore
  • 2,209
  • 1
  • 10
  • 22