If-else statements are pretty straightforward, but there’s a shorter way to write them:
var isEven = true; isEven ? console.log(2) : console.log(1); // 2
— Sorry to interrupt this program! 📺
Given the current situation with COVID-19, times are hard for most of us, but if you're stuck at home you can perhaps use that extra time to work on your front-end skills. Wes put all of his courses at 50% off to help out with the current challenge we're facing.
Plus, these are affiliate links, so if you purchase a course you help Alligator.io continue to exist at the same time! 🙏
condition ? firstExpression : secondExpression;
Ternary operators are easy to understand. It first evaluates if the condition is met. firstExpression is executed if the result is true and secondExpression if false.
One common use case for ternary operators is conditional assignments. You can assign values depending on a specific condition:
var pokemon = 151; var title = pokemon < 152 ? "noob" : "master"; // "noob"