JavaScript: How to use the conditional ternary operator

In addition to “normal” comparison operators (see the links below), JavaScript has a unique comparison operator that can assign values rather than just return a boolean true or false. This is called the “Conditional (Ternary) Operator”.  It follows this syntactical construction:

variablename = (condition) ? value1 : value2

The question mark means: If the condition is true, then variablename is set to value1. Else, variablename is set to value2.

For example, one way to check if someone is old enough to vote is with a traditional if/else block, where the one conditional is evaluated to be either true or false. For example:

var age = 16;

if(age < 18) {
  voteable = "Too young";
}
else {
  voteable = "Old enough";
}

console.log(voteable);

Using the conditional ternary operator, the if/else block can be reduced down to one statement:

var age = 16;

var voteable = (age < 18) ? "Too young" : "Old enough"; 

console.log(voteable);

This is also useful for determining what happens in some random condition. For example, if you have a series of random numbers between 0 and 1 and you want to divide the results such that any random number below 0.5 will be assigned a 2 and above 0.5 will be assigned a 4:

let randNum = Math.random(1);
gameboard[randomSquare.x][randomSquare.y] = randNum > 0.5 ? 2 : 4;

Here is another example of an if block being reduced to one line:

if (colorIndex === 4) {
    colorIndex = 0;
} else {
    colorIndex++;
}

can be reduced to:

colorIndex = (colorIndex === 4) ? 0 : colorIndex+=1;

 

For more information about traditional conditional operators in JavaScript see:
https://www.w3schools.com/js/js_comparisons.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Comparison

For more information about the ternary operator, see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator