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.
//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);
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.
//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);