Any way to toggle between two strings using one piece of JavaScript?

Viewed 27088

I want to do something like

if(something.val() == 'string1')
{
     something.val('string2');
}
else if(something.val() == 'string2')
{
    something.val('string1')
}

But in one line of code. I can't quite remember how it's done, but it involves question marks and colons...

10 Answers

Though, the solutions with a ternary operator are the most readable, you could also use xor from Lodash:

x = _.xor([a, b], [x])[0]

For your specific case:

something.val(_.xor(['s1', 's2'], [something.val()])[0]);

Ref: https://lodash.com/docs/4.17.10#xor

My way was this in a similar situation:

let value = 0

const toggleTwoValues = () => 
  value === 0 ? value = 1 : value = 0

Related