Are booleans objects in JavaScript? Is it true that "everything is an object" in JavaScript?
-
1http://www.diveintojavascript.com/core-javascript-reference/the-boolean-object – Robert Harvey Aug 15 '12 at 23:15
-
For extensive coverage of the Javascript language consult [MDN](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Boolean) – Jordan Arsenault Aug 15 '12 at 23:22
2 Answers
Primitives are not objects, everything else (any standard object) is an object. However, most primitives (all apart from undefined
and null
) have an object counterpart.
So
var a = false;
is not an object, but
var b = new Boolean(false);
is.
Since two objects are only equal if they refer to one and the same object, using the object version of primitives should better be avoided:
a === false; // is true
b === false // is false <- this is a problem
Or especially with boolean objects, using them with any boolean operators will create unexpected results. An object reference always evaluates to true
, so the outcome of using b
would be:
// remember
// a is the primitive value false
// b is a boolean object with value false
// NOT
!a // true
// but
!b // false
// AND
a && true // false
// but
b && true // true
There is no real advantage of using these object versions anyway, since JavaScript is autoboxing primitives when you try to call methods on them. That's why calls like:
var s = "HI THERE!".toLowerCase();
s = s.substring(0,2);
are possible.

- 795,719
- 175
- 1,089
- 1,143
-
1
-
there is a purpose (although not very useful: http://stackoverflow.com/a/856330/908879) _"...is to convert non boolean objects into a boolean"_ – ajax333221 Aug 15 '12 at 23:36
-
1@ajax333221: True, you could indeed use it for type conversion. In this case, you could also use double negation though, e.g. `!!"someString"`. Also it is important to note that there is a difference between calling `Boolean` (and any other of these functions) as function or as constructor. As function they all(?) return primitive values. – Felix Kling Aug 15 '12 at 23:38
-
not conformed with already an accepted answer and +7 votes, he keeps doing awesome edits. If everyone were like Felix Fling, there would probably be world peace and we will likely find cure to most of incurable diseases of today – ajax333221 Aug 15 '12 at 23:52
-
Booleans, numbers and strings are object-like types - they have methods, but they are immutable.

- 2,475
- 21
- 32