13

The following indicates the expression "true instanceof Boolean" evaluates to false. Why would this expression evaluate to false?

$(document).ready(function() {
  
  var $result = $('#result');
  
  if(true instanceof Boolean) {
    $result.append('I\'m a Boolean!');
  } else {
    $result.append('I\'m something other than a Boolean!');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="result"></div>
Allen Tellez
  • 1,198
  • 1
  • 10
  • 14

2 Answers2

19

The value true is a boolean primitive — that's "boolean" with a lower-case "b". It is not an object.

Similarly, "hello" is not an instance of String, because a string primitive is not an object either.

You can test for primitive types with the typeof operator.

The distinction between primitive values and object values can be a little confusing in JavaScript because the language implicitly wraps primitives in appropriate object wrappers when primitives are used like object references. That's why you can write

var length = "hello world".length;

The string is implicitly converted to a String instance for that . operation to work. You can even do that with a boolean:

var trueString = true.toString();

It happens with numbers too, though the syntax gets in the way sometimes:

var failure = 2.toString(); // an error
var success = (2).toString(); // works
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Thanks Pointy, seems instanceOf only works with objects and not primitive types! Good answer. – Allen Tellez Apr 20 '15 at 16:59
  • 2
    Good answer! But a little confusing, maybe tag on a code example to the end for those less familiar: if (typeof true === "boolean") .... – Michael Hays Apr 20 '15 at 16:59
-2

The Boolean object is an object wrapper for a boolean value.

So the boolean value and the wrapper object are not the same thing.

Also, boolean objects are verboten. In other words it isn't good style to ever use a Boolean object.

dcabines
  • 112
  • 4
  • @Shashank yes there are: try `true.toString()` – Pointy Apr 20 '15 at 17:00
  • 1
    You are missing new. Try `new Boolean(true) instanceof Boolean` and you will get true. – dcabines Apr 20 '15 at 17:03
  • @Pointy That's not really an object wrapper. It's just a change to another primitive type, an object wrapper would be like Object(true). – Shashank Apr 20 '15 at 17:03
  • @DavidMichaelCabinessJr. Ah, I was wrong, comment removed. – Shashank Apr 20 '15 at 17:04
  • @Pointy Correct me if I'm wrong, but I believe that's because JS implicitly converts the primitive types to their object forms when you use the dot operator. – Shashank Apr 20 '15 at 17:07
  • @Shashank yes exactly - the '.' operator forces that implicit conversion. (Whether a particular implementation *really* builds a new object or not, I'm not sure; it'd be kind-of hard to tell I guess.) – Pointy Apr 20 '15 at 19:31