Why "true instanceof Boolean" is false in JavaScript

The following shows that the expression "true instanceof Boolean" is false. Why is this expression evaluating to false?

$(document).ready(function() { var $result = $('#result'); if(true instanceof Boolean) { $result.append('I\'ma 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> 
+5
source share
2 answers

true is a boolean primitive - that is, "boolean" with lowercase "b". This is not an object.

Similarly, "hello" not an instance of String, because the string primitive is also not an object.

You can check primitive types using the typeof operator.

The distinction between primitive values ​​and object values ​​can get a little confused in JavaScript, because the language implicitly wraps primitives in the corresponding wrappers of objects when primitives are used as references to objects. That is why you can write

 var length = "hello world".length; 

The string is implicitly converted to an instance of String for this operation . for work. You can do this with boolean:

 var trueString = true.toString(); 

This also happens with numbers, although the syntax sometimes gets in the way:

 var failure = 2.toString(); // an error var success = (2).toString(); // works 
+11
source

The Boolean object is an object wrapper for a boolean.

Thus, the logical value and the wrapper object are not the same thing.

In addition, verboten logical objects . In other words, this is not a good style ever using a Boolean.

-2
source

All Articles