If statements are an essential building block to executing logic within Javascript. Lets take a look at an example of a traditional If/Else statement:
function checkNum(a) {
if (a > 0) {
return "positive";
} else {
return "negative";
}
}
console.log(checkNum(23));
// expected output: "positive"
Ternary operators allow us to write concise If/Else statements, we can write the same function above with a ternary operator like this:
function checkNum(a) {
return (a > 0 ? "positive" : "negative");
}
console.log(checkNum(-6));
// expected output: "negative"
In this function, the condition a > 0 is followed by ? and two expressions. The first expression listed, in this case "positive", will return if the condition is true. The second expression which is separated by : will return if the condition is NOT true. Like so:
condition ? expressionIfTrue : expressionIfFalse
Top comments (0)