Another form of conditional statements is the ternary operator.
Syntax:
condition ? true-block : false-block
The ternary operator is a shorthand for if..else condition and is used to write code quickly. The code inside the true-block is executed when the condition is true and the code inside the false-block is executed when the condition is false.
Like if..else statement, the code for the true-block or false-block needs to be enclosed in curly braces if the block contains more than one statement to be executed.
Example:
var x = 10; x % 2 === 0 ? console.log("Even") : console.log("Odd");
Output:
"Even"
You can also write the code snippet given in the example above as follows:
var x = 10; console.log(x % 2 === 0 ? "Even" : "Odd");
This will produce the same output as given above.