In chaijs/type-detect module, what does this line of code do: {if (obj === Object(obj)) return 'object';}?

54 views
Skip to first unread message

enormouspenguin

unread,
Sep 19, 2014, 4:00:19 AM9/19/14
to nod...@googlegroups.com
if (obj === Object(obj)) return 'object';

That is cut from chaijs/type-detect/blob/master/lib/type.js#L42.

My first guess (probably a joke):

obj === Object(obj)

is somewhat similar to

obj instanceof Object

My second guess is that it's used to distinguish between primitive value (created using literal) and primitive object (created using instantiation) such as 1 and (new Number(1)).

But typeof operator could correctly distinguish by itself:

typeof 1 === 'number'
typeof new Number(1) === 'object'

Also I feel line 41 is unnecessary too:

if (obj === undefined) return 'undefined';

I don't know why would those 2 lines of code be there while

return typeof obj;

in line 43 could as well be enough to substitute both.

Is there any edge case here?

May be I am missing something internal here?

Floby

unread,
Sep 22, 2014, 4:24:36 AM9/22/14
to nod...@googlegroups.com
This code in ChaiJS is used to run some assertions like this
expect(variable).to.be.an('object');

But it does some more clever things than the native typeof operator. For example you could also do this
expect(variable).to.be.an('array');

My guess for that code is that it's a more accurate for testing against an Object.
typeof does a lot of weird stuff like
typeof null => object
typeof [] => object

Simon

unread,
Sep 23, 2014, 12:21:24 PM9/23/14
to nod...@googlegroups.com
This is used to determine if something is a primitive or not.

`typeof null` returns 'object' even though it is not an object and `typeof function() {}` returns 'function' even though it is an object. Basically 'typeof' alone is not enough to determine if something is primitive or object. `instanceof Object` has some edge cases for instance if an object is created with `Object.create(null)` or is from another global context.

enormouspenguin

unread,
Sep 23, 2014, 1:27:37 PM9/23/14
to nod...@googlegroups.com
typeof [] => object
 
Taken cared by this and this.

typeof null => object
 
Taken cared by this.

The cases you mentioned is the well-known ones and was all taken cared of in the code. But the line I am asking makes no sense at all. Maybe, there's still a special case lurking somewhere. Or maybe it's compatibility problem with other JS engines that the code run on.
Any advice on where should I ask to get more details answer on this? Should I go straight to the Issues section of the repo? Or should I go to Stack Overflow or elsewhere? Because it seems that this kind of question I asked isn't getting much interest here. Except you of course, Floby. Many thanks for taking the time to answer.
Reply all
Reply to author
Forward
0 new messages