Ternary Operator
The "ternary operator" is a shorthand way of writing an "if-else" statement in JavaScript.
Ternary operator is also known as the conditional operator because it evaluates a condition and returns one of two values based on the result of the condition.
Syntax
The syntax of the ternary operator is as follows:
condition ? value1 : value2;The condition is evaluated first. If the condition is true, value1 is returned; otherwise, value2 is returned.
Examples
Here are some examples of using the ternary operator in JavaScript:
let x = 10;
let result = x > 5 ? "greater than 5" : "less than or equal to 5";
console.log(result); // "greater than 5"In this example, if x is greater than 5, the value of result will be "greater than 5"; otherwise, it will be "less than or equal to 5".
let y = 3;
let message = y % 2 === 0 ? "even" : "odd";
console.log(message); // "odd"In this example, if y is even (i.e., y % 2 === 0 is true), the value of message will be "even"; otherwise, it will be "odd".
Conclusion
- The ternary operator is a shorthand way of writing an "if-else" statement in JavaScript.
- It is often used to assign a value to a variable based on a condition.
- The syntax of the ternary operator is
condition ? value1 : value2. - The condition is evaluated first, and if it is true,
value1is returned; otherwise,value2is returned.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on
Switch Case
The "switch" statement in JavaScript is used to execute a block of code based on the value of a variable or expression.
For Loops
For loops are a common control flow structure in programming that allows you to repeat a block of code a specific number of times.
© 2026CoderrShyamAll Rights Reserved.