Skip to curriculum
Jump to the editor

1.2. Precise type checks

Easy
Topics
10–20 min

typeof is the first tool for checking a value's type, and it gets several common cases wrong: typeof null is "object", and typeof [], typeof new Date() and typeof {} are all "object" too. instanceof fails for values made in another frame or window, because each frame has its own Array and Object. Code that clones, merges, validates or serializes data needs checks that are exact.

Write four functions in types.js: isNil, isArray, isPlainObject and getType.

Signature

JAVASCRIPT
function isNil(value)          // boolean
function isArray(value)        // boolean
function isPlainObject(value)  // boolean
function getType(value)        // a lower-case string

Requirements

  1. isNil(value) is true only for null and undefined (and a call with no argument). Other falsy values such as 0, "", false and NaN give false, and so do empty objects.
  2. isArray(value) is true for every real array: empty, sparse, and instances of a subclass of Array.
  3. isArray(value) is false for array-like objects (an object with a length, arguments, typed arrays, strings), for null, and for an object that only inherits from Array.prototype.
  4. isPlainObject(value) is true for an object whose prototype is exactly this page's Object.prototype, or null: one made by an object literal, new Object(), Object.create(Object.prototype) or Object.create(null). It is false for an object that inherits from any other object, including one made by Object.create(Object.create(null)) and one whose prototype has a constructor property set to Object. The prototype decides, whatever Symbol.toStringTag the object reports: { [Symbol.toStringTag]: "Custom" } and an Object.create(null) object with a custom tag are plain.
  5. isPlainObject(value) is false for primitives, null, arrays, functions, class instances, built-in objects (Date, Map, RegExp…) and arguments objects, from sloppy and strict-mode functions alike. The arguments object is the one exception to the prototype rule, since its prototype is Object.prototype too, and it stays false even when its Symbol.toStringTag is set to "Object". A Symbol.toStringTag of "Object" does not make any other object plain either. An object literal with its own callee property ({ callee: f }) is still plain.
  6. getType(value) returns "null" for null, the typeof word for every other primitive and for functions, and for any other object the name inside Object.prototype.toString's result, in lower case: "array", "date", "regexp", "map", "set", "error", "promise", "object". Boxed primitives (new Number(1)) are named by what they hold.

Examples

JAVASCRIPT
isNil(null);         // true
isNil(0);            // false
isArray({ length: 0 }); // false
JAVASCRIPT
isPlainObject({ a: 1 });             // true
isPlainObject(Object.create(null));  // true
isPlainObject(new Date());           // false
class Point {}
isPlainObject(new Point());          // false
JAVASCRIPT
getType(null);         // "null"
getType([1, 2]);       // "array"
getType(new Map());    // "map"
getType(new Number(5)); // "number"
getType(() => {});     // "function"

Environment

  • Plain JavaScript in a browser page; the tests call the four globals from types.js.
  • Values made in another frame or window are out of scope for isPlainObject: such an object inherits from that frame's own Object.prototype, and the tests' page cannot reach another frame. isPlainObject only has to recognize this page's Object.prototype.
  • How arguments is recognized: a value is treated as an arguments object when Object.prototype.toString reports Arguments and the value has no Symbol.toStringTag, or when it has an own non-enumerable callee property, which every arguments object is created with. Two forged cases are out of scope and not tested: an object given a non-enumerable callee with Object.defineProperty (it counts as arguments), and a sloppy-mode arguments object whose callee was deleted and whose tag was then changed (no check written in JavaScript can recognize it).
  • Namespace objects such as Math and JSON are ordinary objects whose prototype is Object.prototype, so the prototype rule makes them plain; they are not tested.
  • Any built-in may be used.

Hints

  1. What does Object.prototype.toString.call([]) return? And for new Date()?
  2. What is the prototype of {}? Of []? Of new Point()? Follow each chain one more step.

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…