Ternary Operator(JavaScript)

Japanese version.

The ternary operator in JavaScript, also known as the conditional operator, is used to select one of two expressions based on a condition.

Explanation

It has the following syntax:

condition ? expression1 : expression2

First, the condition is evaluated. If the condition is true, the ternary operator returns the result of expression1. If the condition is false, the ternary operator returns the result of expression2.

Here's an example using the ternary operator:

let age = 20; 
let message = age >= 18 ? "You are an adult." : "You are a minor.";
console.log(message); 

In this example, we check if age is greater than or equal to 18. If age is 18 or older, the ternary operator returns the result, "You are an adult.". Otherwise, it returns "You are a minor.". Since age is 20 in this case, the message variable will be set to "You are an adult.", and that message will be logged to the console.

The ternary operator is useful for creating concise conditional expressions. It can be used as a shorthand alternative to if-else statements for simple conditions. However, it should be used appropriately as complex conditions can lead to decreased readability.

This is useful, for example, when assigning the result of division to a variable and you do not want to generate a zero division.

let a = 10;
let b = 0;
let message = b === 0 ? "-" : (a/b*100).toString() + "%"; 
console.log(message);

---

Links

JavaScript Articles