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 !.

  1. /**
  2. * An improved version of typeof
  3. */
  4. function TypeOf(value) {
  5. const result = typeof value;
  6. switch (result) {
  7. case 'function':
  8. return 'object';
  9. case 'object':
  10. if (value === null) {
  11. return 'null';
  12. } else {
  13. return 'object';
  14. }
  15. default:
  16. return result;
  17. }
  18. }
  19. function IsCallable(x) {
  20. return typeof x === 'function';
  21. }