DONATE  
MENU
HTML
JSON
AJAX
JAVASCRIPT

JavaScript Tutorials

INTRODUCTION

» Introduction to JavaScript

» Practice IT Editor

» JavaScript Example

» JavaScript Placement

» JavaScript Syntax

» JavaScript Statements

» JavaScript Input

» JavaScript Output

» JavaScript Comments

» JavaScript Variables

» Variables' Scope

» JavaScript Operators

» JS Expressions & Concatenation

» JavaScript Data Type

» JavaScript Numbers

» Number Object

» JavaScript Strings

» String Object

» JavaScript Booleans

» Boolean Object

» JavaScript Functions

» JavaScript Arrays

» Array Object - Properties

» Array Object - Methods

» JavaScript Objects

» JavaScript Undefined

» JavaScript Nulls

CONDITIONAL TESTING

» If Statement

» If Else Statement

» JavaScript Ternary Operator

» Switch Statement

LOOPS

» For Loops

» While Loops

» Break & Continue

» For...In Loops

» do...while Loop

FUNCTIONS

» JavaScript Functions

» Creating Functions

» Functions' Parameters

» Functions' Arguments

» Function Invocation

» The Return Keyword

» The Arguments Object

» Callback Functions

» Arrow Functions

ARRAYS

» JavaScript Arrays

» Creating Arrays

» Accessing Arrays

» Looping Arrays

» Multi - dimensional Arrays

OBJECTS

» JavaScript Objects

» Creating Objects

» Prototype Definition

» Accessing Objects

» The this Keyword

AJAX

» Introduction to AJAX

JSON

» Introduction to JSON

JAVASCRIPT DATES

» The Date Object

» Date Methods

» Timing (SetInterval & SetTimeout)

MATH OBJECT

» Math Object

» Math Methods

HTML / JS DOM

» DOM Introduction

» Accessing HTML Elements in DOM

» Get And Change Elements' Contents & Values

» Change Styling - DOM CSS

» DOM Attributes

» JavaScript Event Listeners

» DOM Event Listeners

» JS Events

MISCELLANEOUS

» JS Strict Mode

» JavaScript Hoisting

» JavaScript let keyword

» Reserved Keywords

» JS Best Practices

» JavaScript vs ECMAScript

JAVASCRIPT EXAMPLES

» JavaScript Calculator

.. » JavaScript » Conditional Testing » JavaScript Ternary Operator
Share Tweet WhatsApp

JavaScript Ternary Operator

A ternary operator is a short form or way of writing the if else statement so that it can be used directly in statements and expressions. See a ternary operator as an if else that is contained or is part of an expression or statement. Basically, ternary operators are used in assigning values to variables based on a condition(s). For example, assuming I want to assign a particular value to a variable only when a condition is true else I assign another value to that variable, the usual program will look like,
<script>
var the_gender, gender = "m";

if (gender == "f"){
the_gender = "female";
}
else
{
the_gender = "male";
}

alert(the_gender);

</script>

Copy PRACTICE IT

But then, with the help of the ternary operator, the above if else statement can be simplify and shorten to,
<script>
var the_gender, gender = "m";

//TERNARY OPERATOR IN USE
the_gender = gender == "f"?"female":"male";

alert(the_gender);

</script>

Copy PRACTICE IT

You can see how the ternary operator (gender == "f"?"female":"male") simplified the if else that should have naturally span multiple lines. CREATING A TERNARY OPERATOR Below is how to create a ternary operator,
condition? true value : false value; //SYNTAX

3 < 6?"less than":"greater than"; //A TERNARY OPERATOR

myVar == 4 && theVar < myVar? myVar : theVar; //ANOTHER TERNARY OPERATOR
Above are examples on how to create a ternary operator. First, We specify the condition(s) to be tested and end it with a question mark (?). Next, we specify the value or variable to assign if condition is true and then, a colon (:) to separate it from the variable or value to assign if condition returns false. NOTE: If the ternary operator is contained in an expression. That is, joined with other values using an operator, then the ternary operator must be in parentheses (()). If this is not so, then, the other values in the expression will not only be edged off but your condition won't run properly as you would expect. But if it is not contained in an expression, you may decide to enclose or not enclose it in parentheses. TERNARY OPERATOR IN EXPRESSION
<script>
var gender = "m";

//WRONG WAY
gender = "The gender of this individual is "+gender == "m"?"male":"female";

alert(gender);

var gender = "m";

//RIGHT WAY
gender = "The gender of this individual is "+(gender == "m"?"male":"female");

alert(gender);

</script>

Copy PRACTICE IT

TERNARY OPERATOR NOT IN EXPRESSION
<script>
var num = 1;

//RIGHT
num = num == 1? "One":"Two";

alert (num);

var num = 1;

//RIGHT
num = (num == 1? "One":"TWO");

alert(num);

</script>

Copy PRACTICE IT

It is recommended you enclose your ternary operators in parentheses always as such practices help makes your codes readable. NESTING TERNARY OPERATORS You can nest ternary operators just as you do with if statements. SEE THE IF STATEMENT BELOW,
<script>
var score = 61;
var msg = "";
if (score >= 50){
//NESTED IF ELSE
if (score >= 70){
msg = "QUALITY STANDARD";
}
else if (score >= 60){
msg = "GREAT STANDARD";
}
else
{
msg = "GOOD STANDARD";
}

}
else
{
msg = "Below Standard";
}

alert(msg);

</script>

Copy PRACTICE IT

TERNARY OPERATOR EQUIVALENT
<script>
//THE VARIOUS TERNARY OPERATORS ARE ENCLOSED IN PARENTHESES TO HELP YOU IDENTIFY EACH

var score = 61;
    var msg = "";
    
    msg = (score >= 50? (score >= 70?"QUALITY STANDARD": (score >= 60? "GREAT STANDARD" : "GOOD STANDARD") ) :"BELOW STANDARD");
alert(msg);
</script>

Copy PRACTICE IT

You can see how the ternary operator reduced the multiple lines of the if else if statement to just one line or statement. EXPLAINED First, we defined the main ternary operator,
(score >= 50? NESTED TERNARY OPERATORS WILL BE HERE : "BELOW STANDARD");
Secondly, we nested another ternary operator where it was written in the first that "NESTED TERNARY OPERATORS WILL BE HERE",
(score >= 50? (score >= 70? "QUALITY STANDARD" : ANOTHER TERNARY OPERATOR WILL BE HERE) : "BELOW STANDARD");
Finally, we nested another ternary operator where it was written in the first that "ANOTHER TERNARY OPERATOR WILL BE HERE",
(score >= 50? (score >= 70? "QUALITY STANDARD" : (score >= 60? "GREAT STANDARD" : "GOOD STANDARD") ) : "BELOW STANDARD");
And that was it. You can nest as many ternary operators that your statements and expressions need. SUMMARY
  1. Ternary operators are short forms of if else statements that can be used directly in an expression or statement.
  2. It shortens what can normally be done using the if statement.
  3. A ternary operator comprises of three parts.
  4. The first is the condition(s) that will be tested. We end it with a question mark (?).
  5. The second is the value if the condition is true.
  6. The third is the value if the condition is false.
  7. We separate the two values from each other with a colon (:).
  8. If a ternary operator is contained in an expression, then it should be enclosed in parentheses (()). It is recommended we always enclose our ternary operators in parentheses for readability purposes.
  9. We can nest multiple ternary operators.
Take a short quiz on JavaScript Ternary Operator.
Ask a question or tell us if JavaScript Ternary Operator is easy or not.
cent?

Join our 1,090 subscribers to receive tutorials' updates!

  We won't spam your mail box. We hate it.





StackBeginner 2021 © Joseph Omamode