Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...

like image 288
Bojangles Avatar asked Sep 27 '10 20:09

Bojangles


3 Answers

Try:

something.val(something.val() == 'string1' ? 'string2' : 'string1');

It is called a ternary expression.

like image 97
Matthew Manela Avatar answered Nov 11 '22 18:11

Matthew Manela


Look ma, no ternary operator!

The following works because Javascript short circuits boolean expressions.

If something == string1 then evaluate string2 -- since string2 is a truthy value and the next expression involves the OR operation there is no need to continue. Stop and return string2.

If something !== string1 then it will skip the next operand because if it is false, there is no point in evaluating the next operand (with AND). It will "jump" to the OR operation and return string1.

function toggleString(something, string1, string2) {
   return something == string1 && string2 || string1;
}

something.val(toggleString(something.val(), "string1", "string2"));

If you want the assignment done:

function toggleValue(something, string1, string2) {
   something.val(something.val() == string1 && string2 || string1);
}

toggleValue(something, "string1", "string2"); // something is a jQuery collection

In the end however, I would end up using the ternary operator because this solution might be unclear to other programmers. If you come from Java or other languages, you may expect the function to return a boolean because of all the boolean operators.

like image 9
Cristian Sanchez Avatar answered Nov 11 '22 18:11

Cristian Sanchez


Another way to do it using object properties:

{ 'string1': 'string2', 'string2': 'string1' }[value]

As in the question:

something.val(
  { 'string1': 'string2', 'string2': 'string1' }[something.val()]
)
like image 5
kolossal7 Avatar answered Nov 11 '22 18:11

kolossal7