Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are booleans objects in JavaScript? [duplicate]

Are booleans objects in JavaScript? Is it true that "everything is an object" in JavaScript?

like image 248
beth Avatar asked Aug 24 '26 07:08

beth


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.

like image 73
Felix Kling Avatar answered Aug 25 '26 20:08

Felix Kling


Booleans, numbers and strings are object-like types - they have methods, but they are immutable.

like image 25
Vlad Avatar answered Aug 25 '26 19:08

Vlad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!