×

What is Ternary Operator in JavaScript?

In some cases, a ternary operator can be used instead of an if-else expression. A ternary operator examines a condition and then runs a block of code in response to it. The conditional or ternary operator has been the only JavaScript operator that accepts three operands: a condition, a question mark (?), an expression to execute if the condition is true, followed by a colon (:), and finally an expression to run if the condition is false. As an alternative to an if-else statement, this operator is commonly used.

Syntax

condition ? expression1 : expression2

condition

The value of an expression that is used as a condition.

expression1

If the condition evaluates to a true value, this expression is performed (one which equals or can be converted to true).

expression2

If the condition is false, this expression is performed (it has a value that can be converted to false).

  • The test condition is evaluated using the ternary operator. The ternary operator has three operands, as indicated by its name. Expression1 is run if the condition is true. Expression2 is run if the condition is false. A conditional operator is another name for it.
  • False expressions include null, NaN, 0, the empty string (" "), and undefined. The outcome of the conditional expression will be the result of executing the expression exprIfFalse if the condition is any of these.

Example 1

// program to check if the student has passed or failed
let scored_marks = prompt('Enter your marks :');
// check the condition
let result = (scored_marks >= 40) ? 'You Passed' : 'You Failed';
console.log(` ${result}the exam.`);

Output

Enter your marks: 64
You passed the exam.

Let's say the user types in 64. The condition scored_marks>= 40 is then tested, which returns true. Consequently, the result variable is allocated to the first expression, which is "You Passed".

Example 2

// program to check what to serve
let age = prompt('Enter your age :');
var beverage = (age >= 21) ? "Beer" : "Juice";
console.log(beverage);

Output

Enter your age: 16
Juice

Let's say the user’s age is 16. The condition age >= 21 is then tested, which returns false. Consequently, the result variable is allocated to the second expression, "Juice".

Nested Ternary Operator

The ternary operator is right-associative, which implies it may be "chained" in the same manner as an if... else if... else if... else chain, i.e., You may also stack one ternary operator within another conditional operator as an expression.

Syntax

function example(…) {
    return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;
}
// Equivalent to:
function example(…) {
    if (condition1) { return value1; }
    else if (condition2) { return value2; }
    else if (condition3) { return value3; }
    else { return value4; }
}

NOTE: Nested ternary operators should be avoided wherever feasible since they make your code difficult to comprehend.

Example

// program to check if the student scored good, average or bad
let scored_marks = prompt('Enter your marks :');
// check the condition
let result = (scored_marks >= 40) ? ((scored_marks >= 70) ? 'Good' : 'Average') : 'Bad';
console.log(` You scored ${result} in the exam.`);

Output 1

Enter your marks: 34
You scored Bad in the exam.

Let's say the user scored is 34. The condition scored_marks >= 40 is then tested, which returns false. Consequently, the result variable is allocated to the second expression, "Bad”.

Output 2

Enter your marks: 58
You scored Average in the exam.

Let's say the user scored is 58. The condition scored_marks >= 40 is then tested, which returns true. Consequently, the result variable is allocated to the first expression, which is another condition that checks the condition scored_marks >= 70, which returns false. Consequently, the result variable is allocated to the second expression, "Average".

Output 3

Enter your marks: 82
You scored Good in the exam.

Let's say the user scored is 82. The condition scored_marks >= 40 is then tested, which returns true. Consequently, the result variable is allocated to the first expression, which is another condition that checks the condition scored_marks >= 70, which returns True. Consequently, the result variable is allocated to the first expression, "Good".

Out of ternary operator and if-else does it matter which we use? Which is the quickest? Are there any noteworthy changes in performance? Is it preferable to utilize the smallest code feasible whenever possible?

  • Yes, it matters which we use! The second is much easier to read. You're sacrificing one line that says what you want succinctly for nine lines that are effectively cluttered.
  • If there is any difference in performance, it will be insignificant. Concentrate on developing the most straightforward, readable code possible.
  • Not "as soon as feasible," but "as soon as possible without causing harm." Shorter code is, at the very least, theoretically more legible since it concentrates on the important parts rather than on side effects.

Related Topics

Callback and Callback Hell in JavaScript

The widely used client-side programming language JavaScript is simple, light, and interpretive. JavaScript is used by the majority of client-side web applications. It is also possible to use JavaScript on...

3 minutes read.

Javascript getElementByID

The document.getElementById() method returns the element of specified id. In below example we receive input field by using document.getElementById() method, here document.getElementById() receive input value on the basis of input field...

1 minute read.

What is Ternary Operator in JavaScript?

In some cases, a ternary operator can be used instead of an if-else expression. A ternary operator examines a condition and then runs a block of code in response to...

4 minutes read.

Design a BMI calculator using JavaScript

BMI calculator BMI stands for Body Mass Indicator. It is a numeric value which is calculated based on the height and weight of a person. It represents the fatness of the...

4 minutes read.

Array to String in JavaScript

As a web developer, you often have to deal with multiple data types in a single application. How to convert an array to a string in JavaScript is essential for...

19 minutes read.

Javascript Operators

The concept of operators is the basis of nearly all programming languages used in today's computing systems. Operators facilitate the execution of certain functions. For instance, the (+) symbol is...

8 minutes read.

Javascript Document Object

Document object represents the whole HTML documents. When HTML document is loaded in browser it becomes the document object. It is the root elements that represent the HTML documents. With the help of...

2 minutes read.

Javascript Re-Password Validation

Example <!DOCTYPE html>   <html>   <head>   <script>   function pass_validation()   {   var firstpassword=document.f1.password1.value;     var secondpassword=document.f1.password2.value;     if(firstpassword==secondpassword){     return true;     }     else{   alert("Password does Not Match");     return false;     }     }    </script>   </head>   <body>   <form name="f1" action="/JavaScript/Index" onsubmit="return pass_validation()">   Password:<input type="password" name="password1" /><br/>   Re-enter :<input type="password" name="password2"/><br/>   <input type="submit">   </form>   </body>   </html> Try Now ← Prev Next → ...

1 minute read.

Javascript Date

In JavaScript Date Object is data type build into the JavaScript language. Data object are created with the new Date(). JavaScript Date instance that represents a single moment in time. JavaScript...

2 minutes read.

Functional Programming in JavaScript

Most developers work with object-oriented programming while developing their applications, but sometimes they need to change their approach to solve some specific tasks. Although mostly we tend to go for...

6 minutes read.

JavaScript radio button checked value

What are radio buttons? A radio button is defined as an icon that is used to take input from the user. The user can choose only one option(value) from the group...

5 minutes read.

Javascript String

String object works with series of characters. It is used to store and manipulate text. There are two ways to create string in JavaScript: String literal. Using new keyword. String literal By using double quotes...

4 minutes read.

Javascript Switch Statement

Introduction Conditional statements are simple building blocks in programming languages and are utilized fairly frequently. This portion of Developing Conditional Statements in JavaScript talks about how to utilize the if, else,...

5 minutes read.

JavaScript focus on input

In JavaScript, the elements can be focused using either focus() method or onfocus() event. What is focus() method? When we want to focus on an element (if it can be focused) or...

4 minutes read.

JavaScript redirect URL with parameters

Data can be often passed between web pages as information in URL parameters or query strings. A URL (Uniform Resource Locator) can have a single parameter or multiple parameters.Parameters can...

4 minutes read.

Javascript loops

Loops in JavaScript: Loops are used to execute a specific piece or block of code repeatedly until the given condition is satisfied. What is a Loop? Almost all loops contain a certain...

7 minutes read.

JavaScript Arrays

JavaScript Arrays: JavaScript Arrays are a type of variables that allows us to store the individual or the group of values under a single variable. What is an Array in JavaScript? The array...

6 minutes read.

JavaScript Function

An important part of JavaScript is the ability to create new functions within <script>.....</script> tag. To declare a function in JavaScript using function keyword. We call JavaScript function multiple times to reuse the...

3 minutes read.

Javascript Window Object

The window object represents a window in browser. An object of window is created automatically by the browser. Window is the object of browser, it is not the object of JavaScript. The...

3 minutes read.

Javascript Cookies

Cookie is a piece of data which is sent from a website and stored locally by the user's browser. Cookie is needed because HTTP is stateless protocol. Today most of...

1 minute read.