Using the conditional operator

The conditional operator (also known as the ternary operator) can be use to assign a value to a variable based on a condition.


var NumberOne = 4;
var NumberTwo;
   if (NumberOne == 4) {
     NumberTwo = NumberOne * 3;
   }
   else {
     NumberTwo = "Your number can not be calculated!"
   }
document.write(NumberTwo);

Initially, the variable NumberTwo is declared with no value. The condition says that if the variable NumberOne has the value of 4 then the value of the variable NumberTwo will be the value of NumberOne multiply by 3. If you execute the code then the browser will display the message “12” (which is 4 multiply by 3).

Using the conditional operator allows you to shorten the amount of code you have to write.


var NumberOne = 5;
var NumberTwo;
NumberOne == 4 ? NumberTwo = NumberOne * 3 : NumberTwo = "Your number can not be calculated!";
document.write(NumberTwo);

After the two variables are created instead of starting with the if statement we can write just the condition followed by a question mark. After that we have the two possible values with a colon between them.

If there is only one code to execute in your block then you can even omit the curly brackets and since JavaScript is not concerned with white spaces or line breaks you can even have all code on a single line.


var NumberOne = 4; var NumberTwo;
if (NumberOne == 4) NumberTwo = NumberOne * 3; else NumberTwo = "Your number can not be calculated!";
document.write(NumberTwo);

Or everything on a single line.


var NumberOne = 4; var NumberTwo; if (NumberOne == 4) NumberTwo = NumberOne * 3; else NumberTwo = "Your number can not be calculated!"; document.write(NumberTwo);

Leave a Reply