Skip to content Skip to sidebar Skip to footer

What Are The Pros And Cons Of Using Boolean Type Versus String Type "true"/"false"?

In Javascript, I have seen code using string type to represent 'true' and 'false'. Why not simply use boolean type? What are the pros and cons of using boolean type versus string

Solution 1:

String "true" and "false" are considered to be truthy. So, never use them instead of boolean values.

console.log(Boolean("true"));
# true
console.log(Boolean("false"));
# true

also,

console.log(true  != "true");
# true
console.log(false != "false");
# true

Solution 2:

You should always be using booleans. Using the string "false" as a boolean will still be truthy, since it's not an empty string.

Boolean("true")
>> trueBoolean("false")
>> trueBoolean("")
>> false

Solution 3:

You should use Boolean where possible- among other reasons the compare of a Boolean is much faster to execute than a string compare.

Post a Comment for "What Are The Pros And Cons Of Using Boolean Type Versus String Type "true"/"false"?"