×

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

Javascript Tutorial

JavaScript is a light-weight, dynamic scripting language that is mainly employed to create interactive front-end web applications. It was originally developed in 1995 by Brendan Eich at Netscape Communications Corporation...

5 minutes read.

Synchronous and Asynchronous in JavaScript

JavaScript is a powerful and versatile language that is used all over the web, from small websites to large applications. It is essential for developers to understand the differences between...

9 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.

D3.js Tutorial

Introduction of D3.js D3.js is referred to as a JavaScript library that is used to manipulate the documents according to the data. The intensity of D3 is based on web standards...

5 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 input maxlength

Various attributes often accompany the input tag in HTML to change the properties of the input field. Maxlength() is one such attribute. The maxLength attribute defines the maximum number of characters...

2 minutes read.

Javascript Page Redirect

The window.location object can be used to get the current page address (URL) and to redirect browser to new page. In some websites when we visit, we face a situation where we...

3 minutes read.

JavaScript dropdown onchange

What is onchange event? It is an event in JavaScript used to make the web pages dynamic. The onchange event gets triggered whenever the value of an event changes. It usually...

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.

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 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 Data Types

An Overview of JavaScript Data Types In computing, there are a number of data types, including numbers, strings, and booleans, to name a few. The role of these data types in...

5 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 Forms Validation

Form validation works at server, after client had entered all the necessary details and then pressed submit button. JavaScript provides the facility to validate the form on the client side...

9 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 comment

Introduction In programming languages, comments are a method to include meaningful annotations within the code that the compiler or interpreter will ignore at run time. That is to say, though comments...

7 minutes read.

Javascript Password Validation

Here we see that how to validate any password field. Like password field can be blank and length of password is minimum 8 characters. Example <!DOCTYPE html>   <html>   <head>   <script>   functionpass_validation()   {     var password=document.myform.password.value;     if (password==null || password=="")   {     alert("password can't be blank");     return false;     }   else if(password.length<8)   {     alert("Password must be at least 8 characters long.");     return false;       }     }     </script>   </head>   <body>   <form name="myform" method="post" action="register.php" onsubmit="return pass_validation()" >   Password: <input type="password" name="password">   <input type="submit" value="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.

Javascript Example

What is JavaScript? JavaScript is a highly versatile programming language. It provides the capability to add interactivity to static web pages, which are designed with HTML and CSS. It also provides...

5 minutes read.