How do we use a Ternary Operator in JavaScript?

A Ternary Operator is an alternative to if, else conditions in JavaScript. Unlike other operators that usually take two expressions, a Ternary operator takes three expressions. The expressions are in the form of a condition (first value), followed by two more expressions, which returns the result. See the syntax below.

Syntax

Condition ? first_expression : second_expression

It has two operators, the “?” (Question mark) and “:” (Colon), which separates the condition from the result. If the condition is true, it will evaluate the first expression and it becomes the result. Else, it will look for the result evaluating the second expression.

JavaScript if-else statement

Usually in JavaScript, if you want to perform a conditional check on a given value using if-else condition, then you will end up doing something like this.

<html>
<head>
    <title>Using if-else Statement</title>
</head>
<body>
    Enter an amount: <input type="text" id="bid" />
    <input type="submit" id="Submit" onclick="javascript:CheckBid()" />
</body>
<script>
    function CheckBid() {

        var bid;
        bid = document.getElementById('bid').value;

        if (bid >= 200)
            alert('Its is deal!');
        else
            alert('Too less! Minimum bidding amount 200.');
    }
</script>
</html>
Try it


Ternary Operator Example

Now, let’s see how we can use the Ternary operator to perform a similar check on the value.

<html>
<head>
    <title>Using Ternary Operator</title>
</head>
<body>
    Enter an amount: <input type="text" id="bid" />
    <input type="submit" id="Submit" onclick="javascript:CheckBid()" />
</body>

<script>
    function CheckBid() {
        var result;
        var bid = document.getElementById('bid');

        result = (bid.value >= 200) ? 'Its is deal!' : 'Too less! Minimum bidding amount 200.';
        alert(result);
    }
</script>
</html>
Try it

Simple isn’t it? The result is the same as above. However, it has reduces the length of code and effectively transformed a four line if-else statement into a single statement.

Related: What is a JavaScript Statement?

Conclusion

Although, an if-else statement is conducive for nested conditions, the ternary does not fit in that space. If maintainability is your primary concern (which obviously is), then it is not advisable to use the ternary operator for nested comparisons. Use it when you want to do a simple and quick comparison and automatically it will reduce the length of the code in your application.

← PreviousNext →


Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner

Related Posts: