Mark Miller’s device

This can be omitted at a first reading. Mark Miller is one of the leading JavaScript experts at Google. He’s been credited an ingenious application of call that gives a simple and reliable test for whether or not an object is an array.

This may not sound very much, but it is something that had been puzzling the other experts for some years. For example, Crockford in his Good Parts (published 2008, page 61) gives a much more complex and less reliable solution to this problem.

The moral of this story is that even the experts in JavaScript can have difficulty finding the best way to solve a simple problem.

Test code

TEST('millers-device', function()
{
    var array = [];
    var obj = {};
    var fn = function(){};

    assert( typeof array === 'object' );
    assert( '' + obj === '[object Object]' );

    assert( obj.toString() === '[object Object]' );

    var object_toString = obj.toString;

    assert( object_toString.call(array) === '[object Array]' );
    assert( object_toString.call(fn) === '[object Function]' );

});