Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toggle boolean value equivalent for strings

I know you can do the following in javascript to toggle a boolean in a one liner.

var toggle = false;
if(true) toggle != toggle;

but is this also possible with a string? i know it can be done by some if statements. But is it possible to do it in a oneliner? something like this:

var string_toggle = "CAT";
if(true) "CAT" = "ESP" || "ESP" = "CAT";

If it is not clear what i am asking let me know so i can improve the question.

like image 863
FutureCake Avatar asked Oct 10 '17 16:10

FutureCake


People also ask

How do you toggle boolean value?

The most straightforward way to toggle a primitive boolean variable would be using the NOT operator(!).

How do you convert string false to boolean false?

String str = "false"; Now, use the Boolean. parseBoolean() method to convert the above declared String to Boolean. boolean bool = Boolean.

How do you toggle boolean values in typescript?

To toggle a boolean, use the strict inequality (! ==) operator to compare the boolean to true , e.g. bool !== true . The comparison will return false if the boolean value is equal to true and vice versa, effectively toggling the boolean.

How can I convert a string to boolean in Javascript?

The easiest way to convert string to boolean is to compare the string with 'true' : let myBool = (myString === 'true'); For a more case insensitive approach, try: let myBool = (myString.


1 Answers

You could use the ternary operator.

string_toggle = (string_toggle === "CAT") ? "ESP" : "CAT";

This effectively translates to:

if (string_toggle === "CAT") {
  string_toggle = "ESP";
} else {
  string_toggle = "CAT";
}
like image 63
Mike Cluck Avatar answered Sep 17 '22 01:09

Mike Cluck