2.4 Example coercion algorithms
2.4.1 ToPrimitive()
The operation ToPrimitive()
is an intermediate step for many coercion algorithms (some of which we’ll see later in this chapter). It converts an arbitrary values to primitive values.
ToPrimitive()
is used often in the spec because most operators can only work with primitive values. For example, we can use the addition operator (+
) to add numbers and to concatenate strings, but we can’t use it to concatenate Arrays.
This is what the JavaScript version of ToPrimitive()
looks like:
/**
* @param hint Which type is preferred for the result:
* string, number, or don’t care?
*/
function ToPrimitive(input: any,
hint: 'string'|'number'|'default' = 'default') {
if (TypeOf(input) === 'object') {
let exoticToPrim = input[Symbol.toPrimitive]; // (A)
if (exoticToPrim !== undefined) {
let result = exoticToPrim.call(input, hint);
if (TypeOf(result) !== 'object') {
return result;
}
throw new TypeError();
}
if (hint === 'default') {
hint = 'number';
}
return OrdinaryToPrimitive(input, hint);
} else {
// input is already primitive
return input;
}
}
ToPrimitive()
lets objects override the conversion to primitive via Symbol.toPrimitive
(line A). If an object doesn’t do that, it is passed on to OrdinaryToPrimitive()
:
function OrdinaryToPrimitive(O: object, hint: 'string' | 'number') {
let methodNames;
if (hint === 'string') {
methodNames = ['toString', 'valueOf'];
} else {
methodNames = ['valueOf', 'toString'];
}
for (let name of methodNames) {
let method = O[name];
if (IsCallable(method)) {
let result = method.call(O);
if (TypeOf(result) !== 'object') {
return result;
}
}
}
throw new TypeError();
}
2.4.1.1 Which hints do callers of ToPrimitive() use?
The parameter hint
can have one of three values:
'number'
means: if possible,input
should be converted to a number.'string'
means: if possible,input
should be converted to a string.'default'
means: there is no preference for either numbers or strings.
These are a few examples of how various operations use ToPrimitive()
:
hint === 'number'
. The following operations prefer numbers:ToNumeric()
ToNumber()
ToBigInt()
,BigInt()
- Abstract Relational Comparison (
<
)
hint === 'string'
. The following operations prefer strings:ToString()
ToPropertyKey()
hint === 'default'
. The following operations are neutral w.r.t. the type of the returned primitive value:- Abstract Equality Comparison (
==
) - Addition Operator (
+
) new Date(value)
(value
can be either a number or a string)
- Abstract Equality Comparison (
As we have seen, the default behavior is for 'default'
being handled as if it were 'number'
. Only instances of Symbol
and Date
override this behavior (shown later).
2.4.1.2 Which methods are called to convert objects to Primitives?
If the conversion to primitive isn’t overridden via Symbol.toPrimitive
, OrdinaryToPrimitive()
calls either or both of the following two methods:
'toString'
is called first ifhint
indicates that we’d like the primitive value to be a string.'valueOf'
is called first ifhint
indicates that we’d like the primitive value to be a number.
The following code demonstrates how that works:
const obj = {
toString() { return 'a' },
valueOf() { return 1 },
};
// String() prefers strings:
assert.equal(String(obj), 'a');
// Number() prefers numbers:
assert.equal(Number(obj), 1);
A method with the property key Symbol.toPrimitive
overrides the normal conversion to primitive. That is only done twice in the standard library:
Symbol.prototype[Symbol.toPrimitive](hint)
- If the receiver is an instance of
Symbol
, this method always returns the wrapped symbol. - The rationale is that instances of
Symbol
have a.toString()
method that returns strings. But even ifhint
is'string'
,.toString()
should not be called so that we don’t accidentally convert instances ofSymbol
to strings (which are a completely different kind of property key).
- If the receiver is an instance of
Date.prototype[Symbol.toPrimitive](hint)
- Explained in more detail next.
2.4.1.3 Date.prototype[Symbol.toPrimitive]()
This is how Dates handle being converted to primitive values:
Date.prototype[Symbol.toPrimitive] = function (
hint: 'default' | 'string' | 'number') {
let O = this;
if (TypeOf(O) !== 'object') {
throw new TypeError();
}
let tryFirst;
if (hint === 'string' || hint === 'default') {
tryFirst = 'string';
} else if (hint === 'number') {
tryFirst = 'number';
} else {
throw new TypeError();
}
return OrdinaryToPrimitive(O, tryFirst);
};
The only difference with the default algorithm is that 'default'
becomes 'string'
(and not 'number'
). This can be observed if we use operations that set hint
to 'default'
:
The
==
operator coerces objects to primitives (with a default hint) if the other operand is a primitive value other thanundefined
,null
, andboolean
. In the following interaction, we can see that the result of coercing the date is a string:const d = new Date('2222-03-27');
assert.equal(
d == 'Wed Mar 27 2222 01:00:00 GMT+0100'
+ ' (Central European Standard Time)',
true);
The
+
operator coerces both operands to primitives (with a default hint). If one of the results is a string, it performs string concatenation (otherwise it performs numeric addition). In the following interaction, we can see that the result of coercing the date is a string because the operator returns a string.const d = new Date('2222-03-27');
assert.equal(
123 + d,
'123Wed Mar 27 2222 01:00:00 GMT+0100'
+ ' (Central European Standard Time)');
2.4.2 ToString() and related operations
This is the JavaScript version of ToString()
:
function ToString(argument) {
if (argument === undefined) {
return 'undefined';
} else if (argument === null) {
return 'null';
} else if (argument === true) {
return 'true';
} else if (argument === false) {
return 'false';
} else if (TypeOf(argument) === 'number') {
return Number.toString(argument);
} else if (TypeOf(argument) === 'string') {
return argument;
} else if (TypeOf(argument) === 'symbol') {
throw new TypeError();
} else if (TypeOf(argument) === 'bigint') {
return BigInt.toString(argument);
} else {
// argument is an object
let primValue = ToPrimitive(argument, 'string'); // (A)
return ToString(primValue);
}
}
Note how this function uses ToPrimitive()
as an intermediate step for objects, before converting the primitive result to a string (line A).
ToString()
deviates in an interesting way from how String()
works: If argument
is a symbol, the former throws a TypeError
while the latter doesn’t. Why is that? The default for symbols is that converting them to strings throws exceptions:
> const sym = Symbol('sym');
> ''+sym
TypeError: Cannot convert a Symbol value to a string
> `${sym}`
TypeError: Cannot convert a Symbol value to a string
That default is overridden in String()
and Symbol.prototype.toString()
(both are described in the next subsections):
> String(sym)
'Symbol(sym)'
> sym.toString()
'Symbol(sym)'
2.4.2.1 String()
function String(value) {
let s;
if (value === undefined) {
s = '';
} else {
if (new.target === undefined && TypeOf(value) === 'symbol') {
// This function was function-called and value is a symbol
return SymbolDescriptiveString(value);
}
s = ToString(value);
}
if (new.target === undefined) {
// This function was function-called
return s;
}
// This function was new-called
return StringCreate(s, new.target.prototype); // simplified!
}
String()
works differently, depending on whether it is invoked via a function call or via new
. It uses new.target
to distinguish the two.
These are the helper functions StringCreate()
and SymbolDescriptiveString()
:
/**
* Creates a String instance that wraps `value`
* and has the given protoype.
*/
function StringCreate(value, prototype) {
// ···
}
function SymbolDescriptiveString(sym) {
assert.equal(TypeOf(sym), 'symbol');
let desc = sym.description;
if (desc === undefined) {
desc = '';
}
assert.equal(TypeOf(desc), 'string');
return 'Symbol('+desc+')';
}
2.4.2.2 Symbol.prototype.toString()
In addition to String()
, we can also use method .toString()
to convert a symbol to a string. Its specification looks as follows.
Symbol.prototype.toString = function () {
let sym = thisSymbolValue(this);
return SymbolDescriptiveString(sym);
};
function thisSymbolValue(value) {
if (TypeOf(value) === 'symbol') {
return value;
}
if (TypeOf(value) === 'object' && '__SymbolData__' in value) {
let s = value.__SymbolData__;
assert.equal(TypeOf(s), 'symbol');
return s;
}
}
2.4.2.3 Object.prototype.toString
The default specification for .toString()
looks as follows:
Object.prototype.toString = function () {
if (this === undefined) {
return '[object Undefined]';
}
if (this === null) {
return '[object Null]';
}
let O = ToObject(this);
let isArray = Array.isArray(O);
let builtinTag;
if (isArray) {
builtinTag = 'Array';
} else if ('__ParameterMap__' in O) {
builtinTag = 'Arguments';
} else if ('__Call__' in O) {
builtinTag = 'Function';
} else if ('__ErrorData__' in O) {
builtinTag = 'Error';
} else if ('__BooleanData__' in O) {
builtinTag = 'Boolean';
} else if ('__NumberData__' in O) {
builtinTag = 'Number';
} else if ('__StringData__' in O) {
builtinTag = 'String';
} else if ('__DateValue__' in O) {
builtinTag = 'Date';
} else if ('__RegExpMatcher__' in O) {
builtinTag = 'RegExp';
} else {
builtinTag = 'Object';
}
let tag = O[Symbol.toStringTag];
if (TypeOf(tag) !== 'string') {
tag = builtinTag;
}
return '[object ' + tag + ']';
};
This operation is used if we convert plain objects to strings:
> String({})
'[object Object]'
By default, it is also used if we convert instances of classes to strings:
class MyClass {}
assert.equal(
String(new MyClass()), '[object Object]');
Normally, we would override .toString()
in order to configure the string representation of MyClass
, but we can also change what comes after “object
” inside the string with the square brackets:
class MyClass {}
MyClass.prototype[Symbol.toStringTag] = 'Custom!';
assert.equal(
String(new MyClass()), '[object Custom!]');
It is interesting to compare the overriding versions of .toString()
with the original version in Object.prototype
:
> ['a', 'b'].toString()
'a,b'
> Object.prototype.toString.call(['a', 'b'])
'[object Array]'
> /^abc$/.toString()
'/^abc$/'
> Object.prototype.toString.call(/^abc$/)
'[object RegExp]'
2.4.3 ToPropertyKey()
ToPropertyKey()
is used by, among others, the bracket operator. This is how it works:
function ToPropertyKey(argument) {
let key = ToPrimitive(argument, 'string'); // (A)
if (TypeOf(key) === 'symbol') {
return key;
}
return ToString(key);
}
Once again, objects are converted to primitives before working with primitives.
2.4.4 ToNumeric() and related operations
ToNumeric()
is used by, among others, by the multiplication operator (*
). This is how it works:
function ToNumeric(value) {
let primValue = ToPrimitive(value, 'number');
if (TypeOf(primValue) === 'bigint') {
return primValue;
}
return ToNumber(primValue);
}
2.4.4.1 ToNumber()
ToNumber()
works as follows:
function ToNumber(argument) {
if (argument === undefined) {
return NaN;
} else if (argument === null) {
return +0;
} else if (argument === true) {
return 1;
} else if (argument === false) {
return +0;
} else if (TypeOf(argument) === 'number') {
return argument;
} else if (TypeOf(argument) === 'string') {
return parseTheString(argument); // not shown here
} else if (TypeOf(argument) === 'symbol') {
throw new TypeError();
} else if (TypeOf(argument) === 'bigint') {
throw new TypeError();
} else {
// argument is an object
let primValue = ToPrimitive(argument, 'number');
return ToNumber(primValue);
}
}
The structure of ToNumber()
is similar to the structure of ToString()
.