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";
};
?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With