1condition ? doThisIfTrue : doThisIfFalse
2
31 > 2 ? console.log(true) : console.log(false)
4// returns false
1//ternary operator syntax and usage:
2condition ? doThisIfTrue : doThisIfFalse
3
4//Simple example:
5let num1 = 1;
6let num2 = 2;
7num1 < num2 ? console.log("True") : console.log("False");
8// => "True"
9
10//Reverse it with greater than ( > ):
11num1 > num2 ? console.log("True") : console.log("False");
12// => "False"
1let showme || "if the variable showme has nothing inside show this string";
2let string = condition ? 'true' : 'false'; // if condition is more than one enclose in brackets
3let condition && 'show this string if condition is true';
1var variable;
2if (condition)
3 variable = "something";
4else
5 variable = "something else";
6
7//is the same as:
8
9var variable = condition ? "something" : "something else";
1function example(…) {
2 return condition1 ? value1
3 : condition2 ? value2
4 : condition3 ? value3
5 : value4;
6}
7
8// Equivalent to:
9
10function example(…) {
11 if (condition1) { return value1; }
12 else if (condition2) { return value2; }
13 else if (condition3) { return value3; }
14 else { return value4; }
15}
16
1
2var numOfBottles = 99;
3
4while(numOfBottles > 0){
5
6 // ternary use, instead of using if / else
7 var bottles = numOfBottles < 2 ? "bottle" : "bottles";
8
9 console.log(numOfBottles + " " + bottles + " of beer on the wall.");
10 console.log(numOfBottles + " " + bottles + " of beer,");
11 console.log("take one down, pass it around,");
12 numOfBottles--;
13
14 console.log(numOfBottles + " " + bottles + " of beer on the wall.");
15}