Conditional Ternary Operator

Conditional Ternary Operator

Have you been looking for a shorter way to write an 'if statement' ? Then, this is it. Conditional ternary operator is a shorthand syntax of the more common if and if-else statements. It is used to render or do something based on a specified condition. The syntax is this:

 condition ? expression if true : expression if false

First of all, the condition has to return either true or false. The value returned by the condition determines the expression or block of code that will run. For example,

 let location = 'Lagos';

// using an if statement
if (location === 'Lagos') {
    // ...do something
    console.log('Lagos')
} else {
    // ...do something else
    console.log('Where do you live?')
}


// using a condition ternary operator, it will be expressed as:
location === 'Lagos' ? console.log('Lagos') : console.log('Where do you live?')

From the code above, we can notice:

  • The ternary operator has a shorter syntax.
  • The if statement is more readable for beginners.
  • The condition to be evaluated is put at the left hand side hand of the '?'.
  • If the condition is true, the next expression after the '?' runs.
  • If the condition is false, the expression after the ':' runs.

Also, we can have ternary operators as if-else statements. More than one condition can be specified. Let's see an example:

let location = 'Lagos';

// using an if statement
if (location === 'Lagos') {
    // ...do something
    console.log('Lagos')
} else if (location === 'Abuja') {
    // ...do something
    console.log('Abuja')
} else {
    // ...do something else
    console.log('Where do you live?')
}

    // using a condition ternary operator, it will be expressed as:
    location === 'Lagos'     // condition 1
?   console.log('Lagos')     // if condition 1 is met, run this code
:   location === 'Abuja'     // condition 2
?   console.log('Abuja')     // if condition 2 is met, run this code
:   console.log('Where do you live?')   // if condition 1 and 2 is not met, run this code

From the second example, we can see a ternary operator can also span multiple lines. Feel free to try using ternary operators in your code and let me know if you prefer them to 'if statements'.

I hope you now have a good understanding of what ternary operators are.