2.3 Intermission: expressing specification algorithms in JavaScript
In the remainder of this chapter, we’ll encounter several specification algorithms, but “implemented” as JavaScript. The following list shows how some frequently used patterns are translated from specification to JavaScript:
Spec: If Type(value) is String
JavaScript:if (TypeOf(value) === 'string')
(very loose translation;TypeOf()
is defined below)Spec: If IsCallable(method) is true
JavaScript:if (IsCallable(method))
(IsCallable()
is defined below)Spec: Let numValue be ToNumber(value)
JavaScript:let numValue = Number(value)
Spec: Let isArray be IsArray(O)
JavaScript:let isArray = Array.isArray(O)
Spec: If O has a [[NumberData]] internal slot
JavaScript:if ('__NumberData__' in O)
Spec: Let tag be Get(O, @@toStringTag)
JavaScript:let tag = O[Symbol.toStringTag]
Spec: Return the string-concatenation of “[object “, tag, and “]”.
JavaScript:return '[object ' + tag + ']';
let
(and not const
) is used to match the language of the specification.
Some things are omitted – for example, the ReturnIfAbrupt shorthands ?
and !
.
/**
* An improved version of typeof
*/
function TypeOf(value) {
const result = typeof value;
switch (result) {
case 'function':
return 'object';
case 'object':
if (value === null) {
return 'null';
} else {
return 'object';
}
default:
return result;
}
}
function IsCallable(x) {
return typeof x === 'function';
}