Ternary Operator in JavaScript

← PrevNext →

A Ternary operator takes three expressions. The expressions are in the form of a condition (first value), followed by "two more expressions" that returns the result. Its syntax is... condition ? first_expression : second_expression. The Ternary Operator is an alternative to if, else conditions in JavaScript.

Ternary Operator 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.

Ternary Operator Example

Enter an amount: <input type="text" id="bid" />
<input type="submit" id="Submit" onclick="checkBid()" />

  let checkBid = () => {
      let result;
      let bid = document.getElementById('bid');

      ' Using ternary opertor check the input value.
      result = (bid.value >= 200) ? 'Its is deal!' : 'Too less! Minimum bidding amount 200.';
Try it

Simple isn’t it? Now let's see the same example using if-else statement.

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.

Enter an amount: <input type="text" id="bid" />
<input type="submit" id="Submit" onclick="javascript:checkBid()" />

  let checkBid = () => {
      let bid;
      bid = document.getElementById('bid').value;

      if (bid >= 200)
          alert('Its is deal!');
          alert('Too less! Minimum bidding amount 200.');
Try it

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 →