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.
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 Statement | Description |
---|---|
if statement | Executes a block of code if a specified condition is true. |
else statement | Executes a block of code if the same condition of the preceding if statement is false. |
else if statement | Adds more conditions to the if statement, allowing for multiple alternative conditions to be tested. |
switch statement | Evaluates an expression, then executes the case statement that matches the expression’s value. |
ternary operator | Provides a concise way to write if-else statements in a single line. |
Nested if else statement | Allows 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.
Contact Us