Nelu
Nelu

Reputation: 18710

Is it possible to change the primitive value of a Boolean object in JavaScript?

I know you should never use Boolean objects in JS in place of Boolean primitives. This is just curiosity.

var foo = new Boolean();

Primitive value of foo is now false. How can I change it to true?

Upvotes: 2

Views: 680

Answers (2)

Nelu
Nelu

Reputation: 18710

Turns out you can't. Boolean, String, Number - none of them have methods to change their value because they are immutable. Date does have setter methods, but under the hood the object is probably being discarded and replaced with a new one with the newly set property.

var date = new Date();  // Tue Feb 21 2017 11:28:21 GMT-0600 (CST)
date.setFullYear(2016); // Sun Feb 21 2016 11:28:21 GMT-0600 (CST)

Upvotes: 2

Darion Badlydone
Darion Badlydone

Reputation: 947

The boolean object is just a container of a bool value and it can't be changed.

Moreover, is not advised to use it because it slow down the execution speed and new keyword complicate the code as described in the documentation at:

https://www.w3schools.com/js/js_booleans.asp

Upvotes: 1

Related Questions