25 days ago

What is the specification of primitives and objects in ECMAScript?

Let's take a moment to consider this code:

var a = {}, b = a;
According to the specification, the assignment b = a is equivalent to PutValue(b, GetValue(a)). In turn, GetValue(a) utilizes the GetBindingValue("a", strictFlag) abstract operation, which returns "the value" stored in a. This "value" is, in fact, "the object" to which a was originally assigned. As we know, "the object" is mutable, unlike primitives that are immutable.

However, I couldn't find any mention of "reference values" or "object references" in the specification. Does the enhanced mutability of "the object" indicate a critical divergence from how primitives operate or are there other disparities that we haven't considered yet?

24 days ago
Verified Answer
In JavaScript, variables that are assigned an object value are not given the object itself. Instead, they are given a reference to the object. This reference is a pointer to a location in memory where the object is stored. When you assign an object to a variable, you are actually assigning a reference to that object. So when you assign b = a, you are copying the reference from a to b. Both a and b now point to the same object in memory. Therefore, any changes made to the object through one variable will be reflected in the other variable as well. I hope this helps! Let me know if you have any more questions.


How to get a grip on reference vs value in JavaScript - FreeCodecampPass-by-reference JavaScript objects - Stack OverflowWorking with objects - JavaScript | MDN - Mozilla DeveloperLearning how references work in JavaScript - MediumObject references and copying - JavaScript
25 days ago
Yes, you are correct that in the context of the given code snippet, b = a boils down to PutValue(b, GetValue(a)). When GetValue(a) is called, it uses the abstract operation GetBindingValue("a", strictFlag) which returns "the value" in a. In terms of the specification, "the object" is the reference to an object in memory that is originally assigned to a. The specification defines objects as "a collection of properties, each with zero or more attributes that determine how each property can be used—for example, when the Writable attribute for a property is set to false, any attempt by executed ECMAScript code to assign a different value to the property fails." This means that objects in JavaScript are mutable, while primitives are immutable. Regarding the use of "object references" and "reference values", while these terms are not directly used in the specification, they are commonly used in discussions about JavaScript to refer to the fact that variables holding objects actually hold a reference to the location in memory where the object is stored, rather than the actual object itself. When you assign an object to a new variable, a copy of the reference to the object is made, not a copy of the object itself.