×

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 p5.js

Introduction to p5.js P5.js is a JavaScript library for creative programming. It is built on Processing, a coding environment for creativity. Processing's major goal is to make it as simple as...

4 minutes read.

Javascript Dialog Box

A JavaScript dialog box is predefined function which is used to perform different task. Some functions are used in JavaScript Dialog box. FunctionDescriptionalert()To give alert message to userprompt()To input value from...

2 minutes read.

Javascript Redirect Button

What is a redirect button? When a button acts as a hyperlink, it is known as a redirect button. On clicking the button, it transfers the user to another page. How to...

3 minutes read.

Javascript Email Validation

We can validate the email with the help of JavaScript. Here we check the condition related to any email id, like email it must have "@" and "." sign and...

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 Event

Events are things that happen, usually user action, that are associated with an object. All object have properties and methods. Some objects also have events. The event handler is a command that is...

1 minute 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.

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 setInterval()

On the Window and Worker interfaces, the setInterval() method calls a function or executes a snippet with a specified time delay between each call. This function provides an interval ID that...

4 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 Variable

Variables are used to store values (name="Ram") or expressions (Sum=x+y). Before using of variable first we need to declare it. We use keyword var to declare a variable like this: var name; There are two types of variables: Local Variable ...

1 minute read.

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 moment date difference

Often date differences are required on the web platforms for various reasons. They can be: To find the duration, of course, someone is pursuingTo find the age of a user from...

7 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 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 Number

The Number object is a wrapper object which allows you to work with numerical values. The number object is created using the Number() constructor.It may be integer or floating-point. Syntax var n=new Number(value); Examples <!DOCTYPE html>   <html>   <body>   <script>   var x=100;//integer value   var y=100.7;//floating point value   var z=12e5;//exponent value, output: 1200000   var n=new Number(20);//integer value by number object     document.write(x+" "+y+" "+z+" "+n);   </script>   </body>   </html> Try Now Output 100 100.7 1200000 20 Description The primary...

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