Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ternary operator in JavaScript to invoke two functions

Tags:

Can this be done in JavaScript?

type == 1 ? function1() : function2();
like image 610
Swamy g Avatar asked Oct 31 '09 17:10

Swamy g


People also ask

Can we call function in ternary operator in JavaScript?

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.

How to use if else if in ternary operator?

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

Why use ternary operator JavaScript?

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.

How do you call a ternary operator function?

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.


1 Answers

Yes, that's valid code. It will invoke either function1() or function2(), but not both - depending on the value of type.

like image 179
Jon Skeet Avatar answered Sep 22 '22 05:09

Jon Skeet