Ternary Operators

The ternary operator is basically another way to implement the if-else statement. Now, if it’s just another way to implement the if-else statement, why can’t I use the same old if-else? Why would I need to take up something extra which I don’t need right now?

As for any new change, the answer to the above question is simple. Kinda hard, but it’s worth it. It’s not absolutely necessary to learn it, as you can do anything and everything without it. However, considering the constant evolution of technology, it’s better to learn new things while we still can! After all, learning new things is always interesting.

Let me put this straight. This post is not to blame on the good old if-else statement. If you are not clear on the if-else statement, I would recommend you to google it before you proceed further.

Before we get into what a ternary operator is, let’s get a quick bite on what an operator and operand is, and different kinds of operators in general

Operator:

These are the symbols that we use in our calculations. Ex: + - / = * %

Operand:

These are the variables or constants the are being used with the operator for calculations

There are 3 different types of operators

OperatorDescription
Unary OperatorsRequires one operand. Ex: a++
Binary OperatorsRequires two operands. Ex: a+b
Ternary OperatorsTernary Operators: Requires three operands Ex: c ? a : b

Let’s start with a simple example as usual. A typical if statement looks like below

if (latitude > 0) {
  return 'summer'
} else {
  return 'winter'
}

Let’s put the above statement in a function, so that we can see the actual working result

function getSeason(latitude) {
  if (latitude > 0) {
    return 'summer'
  } else {
    return 'winter'
  }
}

document.write(getSeason(10))

If you want to see how the above code works, I would recommend codepen.io, however if you already know how this works; or, you already are part of another online code editor community, good for you 🙂

Moving on, the getSeason function takes one argument which is the latitude and returns a season string based on the latitude. Ternary operators are all about reducing the number of lines of code. So, before implementing the ternary operator, let’s see if we can reduce the number of lines without it.

If the if-else statement has only one line of code to be executed, then the {} is actually not necessary. The above code can be written as

function getSeason(latitude) {
  if (latitude > 0)
    return 'summer'
  else
    return 'winter'
}

document.write(getSeason(10))

Not much of code reduction here, but the point is, you can avoid the {} in case of one statement within the if-else block

Note:

Anything more than one statement within the if-else would require the {}

Time to implement ternary operator in our above example.

function getSeason(latitude) {
  return latitude > 0 ? 'summer' : 'winter'
}

document.write(getSeason(10))

Looks like the code is reduced a lot now, but how about nested if statements. Let’s take a look at a little more complex example by adding another variable called month to derive the season, like below

function getSeason(latitude, month) {
  if (latitude > 0) {
    if (month >= 1 && month <=6) {
      return 'summer'
    } else {
      return 'winter'
    }
  } else {
    if (month >= 1 && month <=6) {
      return 'winter'
    } else {
      return 'summer'
    }
  }
}

document.write(getSeason(10, 5))

As you can see, the code is a lot more complicated and the number of lines has significantly increased this time. Good news, is the ternary operator can be nested too. The above example can also be written as

function getSeason(latitude, month) {
  return latitude > 0 ? (month >= 1 && month <=6) ? 'summer' : 'winter' : (month >= 1 && month <=6) ? 'winter' : 'summer'
}

document.write(getSeason(10, 5))

Now, all the code in the nested if-else example can be written just in one single line.

On a side note, we can get the current month and current latitude programmatically. The final code now looks like below

function getSeason(latitude, month) {
  return latitude > 0 ? (month >= 1 && month <=6) ? 'summer' : 'winter' : (month >= 1 && month <=6) ? 'winter' : 'summer'
}

new Promise((res, rej) => navigator.geolocation.getCurrentPosition(res, rej)).then(pos => document.write(getSeason(pos.coords.latitude, (new Date().getMonth()+1))))

Make sure to click on Allow when you get the prompt for requesting access to location. Now what is the new statement that I have written to extract the current month and latitude? Well, that is to be discussed in another post! Stay tuned!