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.