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"
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// ternary operators are frequently used as a shorter cleaner if statement
2// condition ? exprIfTrue : exprIfFalse
3
4let age = 15;
5let canDrive = age >= 16 ? 'yes' : 'no';
6// canDrive will be 'no'
7// the condition will be age > 16 which is false so canDrive will equal exprIfFalse
8
9// this ternary is the same as this if else statement
10let age = 15;
11let canDrive;
12if (age >= 16) {
13 canDrive = 'yes';
14} else {
15 canDrive = 'no';
16}
17
18// canDrive will be 'no' because 15 is less than 16
19
20
1// program to check pass or fail
2
3let marks = prompt('Enter your marks :');
4
5// check the condition
6let result = (marks >= 40) ? 'pass' : 'fail';
7
8console.log(`You ${result} the exam.`);