Are booleans objects in JavaScript? Is it true that "everything is an object" in JavaScript?
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.
Booleans, numbers and strings are object-like types - they have methods, but they are immutable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With