This is largely a matter of semantics.
First, let's define boxing, as this term is not commonly used in JavaScript (for example, it is not in the specification):
Boxing is wrapping an object around a primitive value. For example, new Number(42) creates a Number object for the primitive number 42.
The only automatic boxing in JavaScript:
When you use a method in a primitive, like this:
console.log("testing".toUpperCase());
"testing" is a primitive string, and therefore does not have (and cannot have) methods. When the JavaScript engine sees the operation of accessing a property with a primitive root, according to the specification, it creates a wrapper object for this primitive (for example, a String object for a primitive string) before retrieving the property. If a property is called (for example, "foo".toUpperCase() ), the free wrapper object this inside the call (in strict mode, this is a primitive string). If something in the method call does not hold the wrapper object, it is subsequently discarded.
When you use the primitive as the first argument to Function#call or Function#apply in free mode, it is put in a box to be this during the call. (In strict mode, this can be primitive.) If the called function does not save the reference to the wrapper object, it is thrown after the call is completed.
Unpacking is, of course, the opposite: getting the primitive from the box object.
The language in the specification calls boxing "conversion":
From §7.1.13 :
The abstract ToObject operation converts the argument to a value of type Object ...
However, it causes unpacking and "transformations" and "coercion":
From §7.1.1 :
The abstract ToPrimitive operation converts its input argument to a nonobject type
From §4.3.16 :
A logical entity can be cast to a logical value.
From §4.3.19 :
String object can be cast to String ...
In the end, what matters is that we understand what happens when. I suspect that the strict distinction between convert and coercion was not made intentionally by the authors.
source share