Shorter conditional syntax
There are other ways of writing If / Else statements. You will see them all the time in other people’s code.
Removing the braces
As long as it is a single expression on one line, you can remove the { } altogether. Just remember in our mental model, that block is still there.
Ternary Expressions
We don’t get blocks, so you can never write complex logic inside of these. But for simple expressions it’s neat and easy to read:
- Is the expression
code === 'ZA'true? - If so, run
console.log('South Africa') - If not, run
console.log('Unknown')
Be careful with nested ternaries - a chain of ? : looks neat, but quickly gets tricky to read, and easy for bugs to creep in. Generally, if there are multiple conditions, use if/else.
You may also meet switch statements. They only compare for equality, and I rarely use them - if/else is usually shorter and clearer.