Ternary Operator in JavaScript
🎉
Read This on Github
This article is available on Github. You can read it there and contribute to it.
Github Link
Any Issue ?
❓ Syntax of Ternary Operator
Syntax Explain
In JavaScript, the ternary operator (also known as the conditional operator) is a short, concise way to write an if-else statement. It has the following syntax:
condition ? valueIfTrue : valueIfFalse
condition
is an expression that is evaluated to a boolean value (either true or false).valueIfTrue
is the value that will be returned if condition is true.valueIfFalse
is the value that will be returned if condition is false.
📖 Simple Example of Ternary Operator
Simple Example
let x = 10;
let y = (x > 0) ? 'positive' : 'negative';
console.log(y); // Output: 'positive'
- In this example, the ternary operator will evaluate the condition x > 0, which is true because x is greater than 0. Therefore, the value of y will be set to 'positive'.
let a = 10;
let b = 20;
let max = (a > b) ? a : b;
console.log(max); // Output: 20
- In this example, the ternary operator will evaluate the condition a > b, which is false because a is not greater than b. Therefore, the value of max will be set to b, which is 20.
let y = 25;
let z = (y>29) ? console.log("true") : console.log("false")
The ternary operator can be used to concisely write if-else statements that only have two branches, but it is not suitable for more complex if-else statements with multiple branches. In those cases, it is recommended to use a regular if-else statement.
ℹ️
In general, it is recommended to use the ternary operator for simple if-else statements with two branches, and to use a regular if-else statement for more complex if-else statements with multiple branches.
let x = 10;
let y = (x > 0) ? 'positive' : 'negative';
console.log(y); // Output: 'positive'
Here is the same example written using an if-else statement:
let x = 10;
let y;
if (x > 0) {
y = 'positive';
} else {
y = 'negative';
}
console.log(y); // Output: 'positive'