Ternary Operators In JavaScript

Ternary Operators In JavaScript

ยท

2 min read

Introduction

In Javascript, ternary operators are a shorthand way of writing conditional statements. Ternary operators involve three operands:

  • A condition

  • An expression that is to be executed if the condition is true

  • An expression that is to be executed if the condition is false

The syntax of ternary operators is given below:

condition ? expression1 : expression2

In the above code, a condition is any expression that can be evaluated either as true or false. If the condition is true, then the expression1 is executed else the expression2 is executed.

Some Examples

Example 1: Basics

var isTrue = true;
var output = isTrue ? 'Yes' : 'No';
console.log(output); //will print the output as 'Yes'

In the given example, we declare a variable isTrue with a default value of true. Then we use a ternary operator to assign the string 'Yes' to the output variable if isTrue is true. Since isTrue is true, the final result in the console will be 'Yes'.

Example 2: Nested Ternary Operators

var num = 0;
var result = num > 0 ? 'Positive' : num < 0 ? 'Negative' : 'Zero';
console.log(result); //will print the output as 'Zero'

In the above example, we defined a variable num with an initial value of 0. Here, we used a nested ternary operator in case if the variable num is greater than 0 then the string 'Positive' will be displayed, the string 'Negative' would be displayed if the variable num is less than 0 and 'Zero' would be displayed if the variable num is equal to 0.

Since the num variable is equal to 0 then the output in the console will be 'Zero'.

I hope that you must have found this article quite helpful. If yes, then do give a read to some of my other articles!

Who knows you might become a great programmer ๐Ÿค”!

ย