How to use Ternary Operator ( ?: ) In Javascript

The conditional operator, also referred to as the ternary operator (?:), is a shortcut for expressing conditional statements in JavaScript.

Syntax:

condition ? value if true : value if false

Example: In this example, we use the ternary operator to check if the user’s age is 18 or older. It prints eligibility for voting based on the condition.

Javascript
let age = 21;

const result =
    (age >= 18) ? "You are eligible to vote."
        : "You are not eligible to vote.";

console.log(result);

Output
You are eligible to vote.

Explanation: This JavaScript code checks if the variable `age` is greater than or equal to 18. If true, it assigns the string “You are eligible to vote.” to the variable `result`. Otherwise, it assigns “You are not eligible to vote.” The value of `result` is then logged to the console.

Conditional Statements in JavaScript

JavaScript conditional statements allow you to execute specific blocks of code based on conditions. If the condition is met, a particular block of code will run; otherwise, another block of code will execute based on the condition.

There are several methods that can be used to perform Conditional Statements in JavaScript.

Conditional StatementDescription
if statementExecutes a block of code if a specified condition is true.
else statementExecutes a block of code if the same condition of the preceding if statement is false.
else if statementAdds more conditions to the if statement, allowing for multiple alternative conditions to be tested.
switch statementEvaluates an expression, then executes the case statement that matches the expression’s value.
ternary operatorProvides a concise way to write if-else statements in a single line.
Nested if else statementAllows for multiple conditions to be checked in a hierarchical manner.

This table outlines the key characteristics and use cases of each type of conditional statement. Now let’s understand each conditional statement in detail along with the examples.

Similar Reads

JavaScript Conditional statements Examples:

1. Using if Statement...

5. Using Ternary Operator ( ?: )

The conditional operator, also referred to as the ternary operator (?:), is a shortcut for expressing conditional statements in JavaScript....

6. Nested if…else

Nested if…else statements in JavaScript allow us to create complex conditional logic by checking multiple conditions in a hierarchical manner. Each if statement can have an associated else block, and within each if or else block, you can nest another if…else statement. This nesting can continue to multiple levels, but it’s important to maintain readability and avoid excessive complexity....

Contact Us