Skip to content Skip to sidebar Skip to footer

How Do I Compare String And Boolean In Javascript?

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

Solution 1:

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.

Solution 2:

  • If one of the operands is a boolean, convert the boolean operand to 1 if it is true and +0 if it is false.
  • When comparing a number to a string, try to convert the string to a numeric value.

from MDN Equality Operators page

Examples:

true == "true";   // 1 == NaN → falsetrue == "1";      // 1 == 1   → truefalse == "false"; // 0 == NaN → falsefalse == "";      // 0 == 0   → truefalse == "0";     // 0 == 0   → true

Solution 3:

vardata = true;
data === "true"//false
String(data) === "true"//true

This works fine.

Solution 4:

Try expression data == "true"

Tests:

data = "false" -- value will be false

date = "true" -- value will be true

Also, fix your JSON. JSON can handle booleans just fine.

Solution 5:

If its just a json "false"/"true", you can use,

if(! eval(data)){
    // Case when false
}

It would be more cleaner, if you restrict the code to accept only JSON data from server, and always jsonParse or eval it to JS object (something like jquery getJSON does. It accepts only JSON responses and parse it to object before passing to callback function).

That way you'll not only get boolean as boolean-from-server, but it will retain all other datatypes as well, and you can then go for routine expressions statements rather than special ones.

Happy Coding.

Post a Comment for "How Do I Compare String And Boolean In Javascript?"