Tech Junkie Blog: JavaScript : The ? Ternary Operator

Monday, April 10, 2017

JavaScript : The ? Ternary Operator

The conditional ?: operator in JavaScript has three operands the first part goes before ? the second goes between the ? and the : symbol and the third operand goes after the : symbol.  You can think of this operator as shorthand way of writing a an if statement.  The first operand evaluates to a boolean, if the first operand is true then evaluate the second operand else evaluate the third operand.

Let's say we want to want to see what the gender of the baby is and assign it a name, let's demonstrate it with code.

var gender = "girl";

var name = gender === "boy" ? "Julian" : "Julie";

console.log(name);

The code above assigns the variable gender to "girl" then it uses the conditional ?: to assign a value to the variable name if the gender is "boy" then assign the name "Julian" to name, else assign the name "Julie"

Type the code into the browser console you will get "Julie" as name


No comments:

Post a Comment