What are the pros and cons of using boolean type versus string type "true"/"false"?

StackOverflow https://stackoverflow.com/questions/23404028

  •  13-07-2023
  •  | 
  •  

문제

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 type "true"/"false" in Javascript? Or is it simply bad practice to use string type to represent boolean values?

도움이 되었습니까?

해결책

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

다른 팁

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")
>> true

Boolean("false")
>> true

Boolean("")
>> false

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top