How to use Conditional Operator (Ternary Operator) In Javascript

The conditional operator, also known as the ternary operator, is a concise way to write conditional statements in many programming languages, including JavaScript. It takes three operands: a condition followed by a question mark (?), an expression to evaluate if the condition is true, and a colon (:) followed by an expression to evaluate if the condition is false.

Syntax:

let max = num1 > num2 ? num1 : num2;

Example: Finding maximum of two numbers using the conditional operator.

Javascript




let num1 = 80;
let num2 = 30;
let max = num1 > num2 ? num1 : num2;
console.log("The Maximum Value is ", max);


Output

The Maximum Value is  80

Maximum of Two Numbers in JavaScript

Finding the maximum of two numbers is a popular JavaScript operation used in many different programming tasks. This can be accomplished in a variety of ways, each having unique benefits and applications.

There are several approaches for determining the maximum of two numbers in JavaScript which are as follows:

Table of Content

  • Using Math.max()
  • Using Conditional Operator (Ternary Operator)
  • Using Math.max() with Spread Syntax

Similar Reads

Using Math.max()

In JavaScript, you can find the maximum of two numbers using the Math.max() method. This method takes multiple arguments and returns the largest of them. Here’s how you can use it to find the maximum of two numbers:...

Using Conditional Operator (Ternary Operator)

...

Using Math.max() with Spread Syntax

The conditional operator, also known as the ternary operator, is a concise way to write conditional statements in many programming languages, including JavaScript. It takes three operands: a condition followed by a question mark (?), an expression to evaluate if the condition is true, and a colon (:) followed by an expression to evaluate if the condition is false....