jashkenas / underscore

JavaScript's utility _ belt
https://underscorejs.org
MIT License
27.29k stars 5.53k forks source link

whether isObject is correct for new Boolean #2988

Closed yihan12 closed 11 months ago

yihan12 commented 11 months ago
console.log(_.isObject(new Boolean(true))) // true
console.log(typeof new Boolean(0)) // 'object'
yihan12 commented 11 months ago

And these...


console.log(_.isString(new String())) // true
console.log(typeof new String()) // 'object'

console.log(_.isNumber(new Number())) // true
console.log(typeof new Number()) // 'object'

console.log(_.isBoolean(new Boolean())) // true
console.log(typeof new Boolean()) // 'object'

console.log(_.isArray(new Array())) // true
console.log(typeof new Array()) // 'object'
jgonggrijp commented 11 months ago

@yihan12 Thank you for reaching out.

The typeof operator distinguishes only six types: undefined, boolean, number, string, function and object. You will notice that Underscore can distinguish more types than that.

When you do new Number(), you create an object-wrapped number. It is a number and an object at the same time. Consider the following series:

_.isNumber(4) // true
_.isObject(4) // false
_.isNumber(new Number(4)) // true
_.isObject(new Number(4)) // true
_.isNumber({}) // false
_.isObject({}) // true
_.isNumber(new Number(4).valueOf()) // true
_.isObject(new Number(4).valueOf()) // false

Underscore can also distinguish arrays, dates, buffers, maps and many other creatures. The typeof operator would say object to all of those.