The ternary operator is a JavaScript Operator which will return one of two values depending on a conditional supplied. Basically, you supply any conditional which will evaluate out to true or false and it will return one of the two expressions. It is set up as such:
condition ? expression1 : expression2
If the condition evaluates true, then expression1 is returned. If the condition evaluates to false, then expression2 is returned.
Example
var pet = {
name: "Spot",
species: "Dog"
};
var soundMakes = pet.species === "Dog" ? "woof" : "meow";
console.log(soundMakes);
//expected output: "woof"
You can use multiple conditions when evaluating. And you can put functions in the expression section to run complex code.
Example
var aDog = true;
var myPet = false;
aDog && myPet ? function() {
alert("It's my dog");
console.log('Give the dog a treat');
} ()
:
function () {
alert("Not my dog");
console.log('Walk away quickly');
} ();
For more information:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator