/

JavaScript Ternary Operator

JavaScript Ternary Operator

In this blog, we will explore the fundamentals of the JavaScript Ternary Operator and understand how it can be used as a concise way to express conditionals.

The ternary operator is a unique operator in JavaScript that works with three operands. It offers a compact syntax to evaluate conditions and choose between alternative expressions.

The syntax of the ternary operator is as follows:

1
<condition> ? <expression> : <expression>

The <condition> is evaluated as a boolean value. Based on the result of the evaluation, the operator executes the first expression (if the condition is true) or the second expression.

Let’s consider an example. Here, we check if the variable running is equal to true. If it is true, we call the stop() function. Otherwise, we call the run() function:

Example usage:

1
2
const running = true;
(running === true) ? stop() : run()