Conditional Operator
The conditinal operator executes expressions based on a simple check if the condition true or false. Writing this code is also pretty simple and the syntax is as follows:
condition ? exprIfTrue : exprIfFalse
The condition is followed by the operator (?). Then the expression to be executed if "truthy" and the expression if "falsy", seperated by (:).
The conditional operator is used as a quick way of running an "if" statement.
var age = 20; var legalStatus; //using "if" statement if(age >= 21){ legalStatus = "Legal to consume alcohol"; }else{ legalStatus = "Illegal to consume alcohol"; } //using conditional operator legalStatus = (age >= 21) ? "Legal to consume alcohol" : "Illegal to consume alcohol";
The operator is commonly used to hand values that may be null. Type your name in the box then click "Submit", then try it without typing anything.
function nameDisplay(){ var txtName = document.getElementById("yourName") ; var name = txtName.value ? txtName.value : "stranger"; alert("Greetings, " + name); }
When the text box is left blank it leaves a "null" value. It's much easier using the conditional operator for something so simple, but most importantly for checking if a value is null. This operator can also be "chained" similar to "else if" statements.
function example(…) { return condition1 ? value1 : condition2 ? value2 : condition3 ? value3 : value4; } // Equivalent to: function example(…) { if (condition1) { return value1; } else if (condition2) { return value2; } else if (condition3) { return value3; } else { return value4; } } //Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
It makes for easier to read code, and you can probably benefit from using it.