131 total views, 1 views today
If you do any developing with Javascript (or any programming language for that matter), sometimes the the ternary operator can be a great shortcut to replace longer “IF” statements.
It consists of a question mark, a condition, and an expression to execute if the condition is true, followed by a colon and another expression to execute if it’s false.
Let’s say we have a person object
let person = {
name: 'Intern Philly',
age: 24,
driver: null
};
Using an IF statement
if (person.age >= 16) {
person.driver = 'Yes';
} else {
person.driver = 'No';
}
Same thing using one line of code…
person.driver = person.age >=16 ? 'Yes' : 'No';
A few “DON’TS when using the ternary operator:
- Don’t Use Nested Ternaries – They will work, but always remember that someone else may have to read and understand your code. Nesting ternaries inside of ternaries make reading and understanding code you’re unfamiliar with much harder.
- Don’t Do Assignments Inside Ternaries – Your code can be simplified by doing the assignment afterwords. We prefer to write our code so that the assignment happens after the ternary is resolved.
Try to keep the ternaries simple and readable. Make sure to always follow the best practices!
No responses yet