1

I would have guessed only 2. True/False. Howerver from underscore.js check for Boolean types, we have:

_.isBoolean = function(obj) {
    return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
  };

I would have thought checking for a value of true or false would have been sufficient, but b.c. of the 3rd operand

 toString.call(obj) == '[object Boolean]'

there must be other values?

  • 4
    There are `Boolean` **objects**, that are not equal to true or false – Ian Jun 20 '13 at 14:27
  • Then what's the point of their existence if they can't be equal to true/false? – nice ass Jun 20 '13 at 14:28
  • See http://stackoverflow.com/questions/856324/what-is-the-purpose-of-new-boolean-in-javascript – user123444555621 Jun 20 '13 at 14:29
  • @the_web_situation Well, it's too late, too many people answered. Anyways, hopefully this helps: http://jsfiddle.net/5Hxj7/ – Ian Jun 20 '13 at 14:31
  • @the_web_situation I'm not sure they're actually *used* much, but from the examples the answers show, it's possible that a primitive be autoboxed to an Object, so this is just a safecheck for those slim chances. Because of short-circuiting, the extra check shouldn't be called except for those rare occasions – Ian Jun 20 '13 at 14:40
  • 1
    the only correct answer got deleted ... here is a real world example ... http://jsfiddle.net/tr2by/ –  Jun 20 '13 at 14:41
  • Brilliant, where did answer #5 go ? –  Jun 20 '13 at 14:43
  • @the_web_situation I don't know, I think lonesomeday scared him off with with his incorrect claims. I was just commenting on the answer because lonesomeday's comment didn't make sense, and was trying to prove it was a good example – Ian Jun 20 '13 at 14:45

3 Answers3

1

The method checks to see if the value is either a boolean primitive (true or false) or if it's an instance of the Boolean built-in object type. In other words, there are two types involved, so it's checking for both.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

There are also Boolean Objects which are not the same as the primitive (but still Boolean nonetheless):

new Boolean(false) == false // true
new Boolean(false) === false // false
Daff
  • 43,734
  • 9
  • 106
  • 120
1

Try this:

var bool = new Boolean();

This constructs a new Boolean object. Now, presumably, a boolean must be true or false, correct?

bool === true; // returns false
bool === false; // returns false

So it's a boolean, but neither true nor false. This is the circumstace that underscore is catering for.

The reason is that it is a Boolean object. true and false are Javascript primitives. No object is ever equal to a primitive or indeed to any object other than itself.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • @the_web_situation I can't imagine ever using this in my own code. Underscore is a library, however, so has to deal with the strange things programmers do. *shrug* – lonesomeday Jun 20 '13 at 14:39