DEV Community

Cover image for Tenary Operators in JavaScript, Should I?
Osumgba Chiamaka
Osumgba Chiamaka

Posted on

Tenary Operators in JavaScript, Should I?

Tenary operators are said to replace the if-else statements. When and how should tenary operators be used? In this article we would learn what tenary operators are and how it can be used.

Prerequisite

  • Basic JavaScript understanding

Tenary operators

Operators are used to assign, compare, evaluate one, two or more operands. We have different types of operators in JavaScript. These include comparison, arithmetic, logical, tenary, etc.
Tenary operators have 3 operands and are often used as a shorthand for if statement. Tenary operators are represented with ?:

Let’s retrace out steps back to our if-else statement.

    if (condition) {
      expressionIfTrue
    } else {
      expressionIfFalse
    }

The if-else statement takes a condition which will evaluate to be either truthy or falsy. The if-else statement above can be rewritten with tenary operators.

Syntax

    condition ? <expressionIfTrue> : <expressionIfFalse>

e.g
show

The first operand is the condition to be evaluated. it’s like asking a question - age > 18 ?.
If the condition evaluates to be truthy the second operand after ? is executed, if the condition evaluates to be falsy the third operand after : is executed. Some falsy values includes, false, null, NaN, 0, an empty string (""), and undefined.

Tenary operators present a very concise way to write your if-else statements, but should this replace your if-else statements in a codebase. Though they can be used interchangeable, tenary operators return a value while if-else do not because tenary operator is an expression while if-else is a statement.

Nested Tenary operators

Similar to the multiple if-else statement, we can chain our tenary operator to evaluate multiple conditions.

    let books
    if (booksTitles.includes(title)) {
        books = booksTitles
    }
    else if (!title) {
        books = {}
    }
    else {
        books = booksTitles.concat(title)
    }
    const books = booksTitles.includes(title) ? booksTitles
        : !title ? {}
        : booksTitles.concat(title)

Tenary operators when used in a codebase can look shorter.

Should Tenary replace if-else ?

Readable codes

Tenary operators are a good replacement for one line if-else statement. Chained or nested tenary on the other hand can get confusing as the condition continues to grow. If you must use nested tenary, formatting is very important.

    return age > 10 ? 'teenager' : age >= 18 ? 'adult' : 'child'
    return age > 10 ? 'teenager'
      : age >= 18 ? 'adult'
      : 'child'

Debugging

Nested or chained tenary operators are slightly difficult to read and debug because you can not add break points on each sub expression. The sample code below is easier for a debugger, to isolate each break point.

    if (age > 10) {
      return 'teenager'
    }
    else if (age >= 18) {
      return 'adult'
    }
    else {
      return 'child'
    }

Conclusion

The decision to use tenary operators is up to you and your team. Because tenary operators look shorter, this shouldn’t be the reason to replace your if-else statements entirely with tenary operators most especially nested if-else statement. While working in a team, do not write codes that will take your team members hours just to understand, thus making debugging harder.

I use tenary and I love it especially when it’s one line if-else statement. Always remember that "shorter codes does not equal cleaner codes"

I hope you enjoyed this post. You can find me on Twitter, let's connect.

Top comments (2)

Collapse
 
functional_js profile image
Functional Javascript

Nice comprehensive analysis Osumgba.

I use ternaries when it's a pretty simple conditional and need one of two possible values returned.

They are especially helpful in creating single line functions, for example....

/**
@func
find the largest word in an array

@param {string[]} a
@return {string}
*/
const getLongestStrInArr = a => a.reduce((biggest, curr) => curr.length > biggest.length ? curr : biggest);

//@tests
const aWords = ["a", "abcde", "", "abc", "abcd"];
console.log(getLongestStrInArr(aWords)); // abcde
Collapse
 
osumgbachiamaka profile image
Osumgba Chiamaka

Tenary operators are amazing especially in simple conditioning, but can get completed when you start nesting them.