Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 'true instanceof Boolean' equal to false in JavaScript [duplicate]

Tags:

javascript

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>
like image 472
Allen Tellez Avatar asked Apr 20 '15 16:04

Allen Tellez


1 Answers

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
like image 172
Pointy Avatar answered Sep 28 '22 10:09

Pointy