Boxing and coercion are two distinct concepts that can occur independently, together, or not at all.
- Boxing involves encapsulating a primitive value within an object.
- Coercion, on the other hand, is akin to interpreting a primitive as a different type.
If you observe boxing converting the type of a given value, it is considered a combination of both conversion and boxing.
For example:
var sp = 'abc'; // string primitive
// boxing
var so = new String( sp ); // string object, created from string primitive
// first conversion and then boxing
var sn = new String( 123 ); // string object, created from a number
// coercion without boxing
var n = '3' - 1; // number 2
It is uncertain whether the coercion at '3' - 1
is executed by the same part of the JavaScript engine as the conversion at new String( 123 )
, but it is plausible to view it this way.
Boxing can be utilized for operations that can only be performed with objects, like:
var s = new String('a');
s.id = 123
// --> String { 0: "a", id: 123, length: 1 }
I have never found the need to explicitly use boxing, only implicitly as seen in examples like "abc".charAt(0)
.
(opinion:)
In my interpretation, the term coercion underscores the aspect that it occurs implicitly within a context of different types, contrasting with words like casting or conversion. This implies that coercion is always implicit and cannot be consciously performed. Instead, the rules of coercion can be leveraged to enforce a specific type, as demonstrated by examples such as '' + 3
for conversion. Explicit conversions like +'3'
or Number('3')
are not considered coercion. (The specification lacks a clear differentiation here.)
To summarize in a subjective manner:
- Boxing involves encapsulating a primitive value within an object.
- Coercion is a process that occurs naturally, not something actively executed.
- Conversion can be carried out explicitly or by utilizing boxing or coercion.