Toggle boolean equivalent value for strings

I know that you can do the following in javascript to switch the boolean value in one liner.

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

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

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

If it is not clear what I ask, let me know so that I can improve the question.

+4
source share
2 answers

You can use the ternary operator .

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

This effectively means:

if (string_toggle === "CAT") {
  string_toggle = "ESP";
} else {
  string_toggle = "CAT";
}
+3
source

If you are a heavy user, why not make some kind of class? overkill

Here im uses this javascript syntax.

ECMAScript 6, !

class ToggleValue {

  constructor(value1,value2){
    
    this.values = [value1,value2]
    this.pointer = 0
  
  }
  
  toggle(){
    
     this.pointer = +!this.pointer
    
  }
  
  valueOf(){
  
    return this.values[this.pointer]
  
  }
  
}



var dupaOrGrabowa = new ToggleValue('dupa', 'grabowa')

dupaOrGrabowa.toggle()
console.log(dupaOrGrabowa + '')
dupaOrGrabowa.toggle()
console.log(dupaOrGrabowa + '')
Hide result
+1

Source: https://habr.com/ru/post/1687249/


All Articles