JavaScript language supports a C style ternary operator, also called a conditional operator. Any variable can be assigned value based on boolean value of an expression.
Syntax
var <variable_name> = (<expression or condition>)?value 1:value 2;
The new variable will get its value based on certain conditions, suppose the condition is true, then the value 1 will be assigned, otherwise value 2 will be assigned.
There are many usage of such type of conditional operator. For example, if the variable is above or below certain range we can use conditional operator to decide the actual value of the variable.
Example #1
//variable declaration
var price = prompt("Enter the price of the item:");
var real_price = Number(price); // string price converted to numeric equivalent
var high-or-low = (real_price < 1000)? "Low Price":"High Price";
console.log(high-or-low);
Output #1
When you run the program you get a prompt asking you to enter the price of the item. Enter a random number to test.
Then press OK to see the result. The value of variable is displayed based on whether it is high or low.
Consider one more example, where we check if the shape is rectangle or a square based on the area.
Example #2
//variable declaration
var area = 0;
var height = prompt("Enter Height");
var real_h= Number(height);
var length = prompt("Enter Length");
var real_l = Number(length);
area = real_l * real_h;
var shape_type = (real_l === real_h )? "Square":"Rectangle";
console.log(shape_type);
console.log("Area ="+ " " + area);
Output #2
The conditional operator save the extra code to write a conditional block such as if-else block in JavaScript. Also, there is an immediate variable assignment after the code executed successfully. There is not need to write an explicit return statement.