When should I use Boolean instead of boolean?. I mean, why would I want to have a null value in a variable which should contain either "true" or "false".. One spontaneous answer (of most people) would be if the value is unknown. i.e, if we don't know whether the value is true or false. But from a programming perspective, I think using Boolean may break the code as we will not know whats inside. So, I think using the primitive type is better than the wrapper.. Correct me if I am wrong.
It is recommended that you use the Boolean() function to convert a value of a different type to a Boolean type, but you should never use the Boolean as a wrapper object of a primitive boolean value.
boolean is a primitive and Boolean is as object wrapper. So boolean, is the type whose values are either true or false while the other is an object. If you wanted to convert a string to a boolean you could try Boolean.
In computer science, a boolean or bool is a data type with two possible values: true or false. It is named after the English mathematician and logician George Boole, whose algebraic and logical systems are used in all modern digital computers. Boolean is pronounced BOOL-ee-an.
Uppercase Boolean is an object type. Lowercase boolean is a primitive type. You should always use boolean (the primitive type in your programs). This is because, the Typescript type system does not force an object to its primitive type, while JavaScript does.
Generally speaking, the wrapper classes are used in cases where an object is required or strongly preferred. Outside of these situations, it's better to use the primitive types, since they have lower overhead, you can use ==
, etc. There are two and a half major situations where this is frequently seen:
Future
, you have to use a Boolean
instead of a boolean
. (HT @user949300)NULL
value that might be present in the database. It's usually still better to forbid nulls and use a primitive for booleans, though, since semantically a default is usually better than "undefined".Since boolean values are restricted to either true
or false
, it's uncommon to see them used in Collections or Generics; generally speaking, if you'd have a boolean as a value, you'll just use Collection#contains
instead.
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