How do I compare string and boolean in Javascript?

user605334 picture user605334 · Apr 14, 2011 · Viewed 45.8k times · Source

I got the Json "false" from server. I respond as bool but it's Json so it's in browser type is String instead of bool.

So if I run (!data) whenever I want to check "false" == false then they not worked.

So how can I parse bool from String in JavaScript then?

"true" == true and "false" == false. Then the code (!data) can check what it is [true and false]

Answer

alex picture alex · Apr 14, 2011

I would just explicitly check for the string "true".

let data = value === "true";

Otherwise you could use JSON.parse() to convert it to a native JavaScript value, but it's a lot of overhead if you know it's only the strings "true" or "false" you will receive.