Ternary Operator: Solutions Shortcut

Ternary Operator: Solutions Shortcut

Discussing the one the most used conditional operators as far as JavaScript is concerned. A detailed implementation of the usage of ternary operator.

Traditional Approach

When it comes to problem-solving, we have always been using conditional statements since we started programming. The most well-known are:

  1. if: Used to execute a block of code if a specific condition is met

  2. else: When the same condition is false (statement inside if), the execution of a block of code is specified.

  3. else if: If the first condition is false, this defines a new test.

  4. switch: used to specify many alternative blocks of code to be executed

These above statements come in very handy when a decision is to be made and further execution has to take place. The program will take its route based on the conditions provided. But what if I told you there is a shortcut to use the "if-else" statement which takes in less code and gives the same results? Let us look at an example and understand it.

Example-1: For a given input, check whether the given number is even or odd.

Now we will use our traditional method of solving this problem statement.

const oddEven = number => {
    if(number %2 === 0){
        return "Even";
    }
  else
      return "Odd";
}

console.log(oddEven(5)); // Odd

The above oddEven function is called and it prints that the number is 'Odd'. Now let us look at the ternary operator and solve the same problem

const oddEven = number => number %2 ===0 ? "Even" : "Odd";

console.log(oddEven(5)); //Odd

Did you see how little code we have written for the same example? This is the magic of the ternary operator. So what exactly is this thing and how do we use it?

Ternary Operator: A better method

The word 'ternary' means "consisting of or involving three" and it does resonate with our ternary operator because our operator takes in three parameters

  1. Condition

  2. The expression if the condition satisfies(truthy)

  3. The expression if the condition fails(falsy)

The Syntax for the ternary operator is

condition? truthy : falsy

The condition is based on the need and once the test cases have been written, it is separated by a question mark ?. It is mandatory to check all the conditions before the ?. Next comes the truthy, which contains the expression if the condition is satisfied. If the condition is false, the falsy expression is returned.

Taking the example we took above we took the i.e. number %2 ===0 ? "Even" : "Odd"; we are checking whether the number gives remainder 0. If did not give zero and that is why Odd was printed in the console.

Let us take another example to understand ternary better

Example-2: Check whether the given number is between 0-50 and return its square. If it is above 50, double the number and display it.

const rangeFinder = number => (number>0 && number <50) ? (number* number) : (number*2);

console.log(rangeFinder(55)); //110

As you can see, the input given was 55 and the operation went the following way

  1. Function rangeFinder() is called and input is given 55.

  2. The function takes in the argument and starts checking for the condition.

    • If the number falls between 0 and 55, or

    • It is greater than 50

  3. Since the input is greater than 50, the ternary operator does not execute the 'truthy' statement i.e returning the square, (number* number)

  4. Thus, the falsy statement will get executed, and the function rangeFinder() will return the number after doubling it, (number*2) and we get the output 110 in the console.

In short, the ternary operator is a great alternative for 'if-else' and results in less writing and more readability. I hope you have cleared your doubts and shortcomings regarding the ternary operator. Here are some output-based questions for further practice.

Practice Questions

Q1 -->

// program to check the array size 

const numbers = [1,2,3,4,5,6];
let sizeMsg = numbers.length > 5 ? 'The numbers array is large' : 'The numbers array is small';

console.log(sizeMsg); //The numbers array is large

Q2 -->

// program to check if number is positive, negative or zero

let a = 10;
let result = (a >= 0) ? (a == 0 ? "zero" : "positive") : "negative";
console.log(`The number is ${result}.`); //The number is positive

Q3 -->

//program to check if string length is greater than 4 or not
let sizeMsg = strInput => strInput.length > 4 ? 'String length in greater than 4' : 'String length is shorter than 4';
console.log(sizeMsg("Pineapple")); //String length in greater than 4