Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore.js _.isObject = function (obj) { return obj === Object(obj); };

When we view Underscore.js source code, we can see the following:

    _.isObject = function (obj) {
    return obj === Object(obj);
};

I know it works.

But why not use this:

    _.isObject = function(obj){
    return typeof obj ==="object";
};

?

like image 261
gongeek Avatar asked May 08 '14 15:05

gongeek


2 Answers

The difference is with the tricky value null. typeof null returns 'object', which is obviously quite confusing and not the desired result.

However, using the object constructor with null results in the creation of a new object (see MDN). This means that you can distinguish between objects and null, which typeof cannot do.

like image 76
lonesomeday Avatar answered Nov 10 '22 00:11

lonesomeday


why not use typeof obj === "object"

Because that's not what we wanted to test. The _.isObject function is supposed to return whether the argument is a reference value (i.e. an object, to which you can add properties) and whether it is not a primitive value.

The typeof operator is not reliable for that. It yields "object" for the value null as well, and does not yield "object" for callable objects (i.e. functions).

Instead, we can use the Object function which will try to "cast" its argument to an object via ToObject, and will yield the argument exactly in the case when it already is an object.

like image 28
Bergi Avatar answered Nov 09 '22 22:11

Bergi