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.

function checkCountryCode(code){
    if (code === 'ZA') console.log('South Africa')
    else if (code === 'GH') console.log('Ghana')
    else console.log('Unknown')
}

Ternary Expressions

code === 'ZA' ? console.log('South Africa') : console.log('Unknown')

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:

  1. Is the expression code === 'ZA' true?
  2. If so, run console.log('South Africa')
  3. 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.