Then what's in JavaScript

? - or ternary operator

One two or three operators

Javascript operations work with operators, the most important of which are +, -, /, =, * and%. Operators can be assigned to three types:

Unary operators, also single-digit combinations
An operand before or after the operator
Negation or negation:! N, x2
Two-digit (binary) operators
Two operators: one before and one after the operator
Addition a + b
Triple (ternary) operators
Three operators, short form of an if-then-else query
t = age < 16="" "10€"="" :="" "50€"="">

Ternary will be at simple if then else Conditions used when the result of the condition true or false is.

if (age <18) {// condition serveApfelsaft (); // true} else {serveWein (); // false}

Instead of the lengthy if then else statement, the conditional assignment is made using the ternary operator.

The ternary operator has three operands: the first operand is the condition, the second operand is returned if the condition true returns and the third operand is returned if the condition false supplies.

Operand 1 Operand 2 Operand 3 | | | let foo = (condition)? if true: if false;

Before you have really used the Ternary notation, you can structure the expression clearly:

tour.finished = tour.walked> 10? "Tour successfully completed": "not yet gone far enough";

The result of the condition - in the example tour.walked> 10 - should be true or false, the result is the string "Tour completed successfully" or "not yet walked far enough".

Example for Ternary

Instead of

let member = document.getElementsByName ("member"); let ticket; for (let i = 0; i <2; i ++) {member [i] .onclick = function () {if (this.value === "1") {ticket = "€ 10"; } else {ticket = "€ 50"; }}}

one line is enough:

+ - condition | ticket = (this.value === "1")? "€ 10": "€ 50"; ^ ^ | | Condition applies --- + + --- binding does not apply

It reads: If a member is elected, the ticket costs € 10 and otherwise € 50. The ternary operator saves a few lines and the creation of a new variable with simple if… else statements.

Ternary useful or not useful?

Some say a ternary operator instead of if then else contributes to the clarity and legibility of the script code, because instructions in one line are easier to understand. The others say if-then statements are easier to read and produce the more efficient code when compiling.

Ternary can be useful in simple Boolean queries in which it saves one or two lines of script code. Here we are on a homeopathic level of optimization.

External sources