What is a Ternary Operator?
According to MDN,
In simple terms, Ternary Operator is one that takes three operand, the first being the condition (just like if) ,followed by a question mark (?) Asking for what to do if it's true, then the expression to be executed , followed by colon(:) to log the else part of the logic which the expression will follow if falsey.
See example below
var firstName = 'Abraham'; var age = 16; /*using Ternary Operator to determine the kind of drink he takes based on his maturity NB: below 18 takes Juice above 18 takes Soda t */ ↗️ condition. ↗️ Execution if truthy age >=18 ? console.log( firstName + ' drinks Soda ') : console.log( firstName + ' drinks Juice'); ⬇️ else part of the argument and its declaration. // console logs Abraham drinks Soda 🍺 (because of his age)
Also , Ternary Operation can be used in variable assignment, i.e to attribute two values to a single variable, to be assigned based on condition.
See illustration below
/*let's assign values to a course variable depending on students academic level */ var level = 500; var course = level >=200? 'depertmental': 'borrowed' ; // console logs departmental for any level above 200 // and borrowed for anything apart from that. /* This is possible because, JS equality Operator does its assignment from left to right i.e the Ternary operation is firstly carried out before iy being assigned to the variable 'course' */