Can this be done in JavaScript?
type == 1 ? function1() : function2();
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement. A ternary operator is written with the syntax of a question mark ( ? ) followed by a colon ( : ), as demonstrated below. In the above statement, the condition is written first, followed by a ? .
The JavaScript ternary operator is a useful tool that you'll encounter in code quite often. Ternary operators can make statements more concise and easy to reason about. If the syntax is new to you, the operator may seem a little confusing.
Make sure the functions doThis and doThat return a value of type int. If you really want a one-line If Else , just write it as one line: if (condition) doThis(); else doThat(); Granted, the ternary operator (if it worked the way you thought) would be shorter, but terseness isn't always a good thing.
Yes, that's valid code. It will invoke either function1()
or function2()
, but not both - depending on the value of type
.
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