I am trying to use ? to decide which method i want to call, but i do not need to assign a variable. My question: Is there a way to use the ternary operator with out assigning a variable?
(something i dont need) = (x == 1)? doThisMethod():doThatMethod()
instead of
if(x == 1) {
doThisMethod()
} else {
doThatMethod()
}
Nope, you can only assign values when doing ternary operations, not execute functions.
We can nest ternary operators to test multiple conditions.
A Ternary Operator in Javascript is a special operator which accepts three operands. It is also known as the "conditional" or "inline-if" operator. Ternary Operator in Javascript makes our code clean and simpler. It can be chained like an if-else if....else if-else block.
This will not work, as it is not the intended use of the ternary operator.
If you really want it to be 1 line, you can write:
if (x==1) doThisMethod(); else doThatMethod();
I doubt that this works. The JLS §15.25 defines the ternary expression as follows:
ConditionalExpression:
ConditionalOrExpression
ConditionalOrExpression ? Expression : ConditionalExpression
And a ConditionalExpression
isn't a Statement
by itself. It can be used in various other places, though, e.g. an Assignment
:
AssignmentExpression:
ConditionalExpression
Assignment
Assignment:
LeftHandSide AssignmentOperator AssignmentExpression
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With