Ternary operator javascript Code Example

Last Updated On Thursday 18th Aug 2022

In this tutorial you will be learn how to use the JavaScript ternary Operator to reduce your code.

	condition ? exp1 : exp2

Clean shorthand for an if statement.

Ternary operator – is frequently used as a shortcut for the if-else statement.

  • condition is a boolean expression (true or false)
  • exp1 is returned if the condition evaluates to true
  • exp2 is returned if the condition evaluates to false

without ternary operator

	if (8 < 2) {
    console.log("if block");
} else {
    console.log("else block");

with the ternary operator

	(8 < 2) ? console.log("if block") : console.log("else block")


Use the JavaScript ternary operator (?:) to reduce the your code.

ternary operator
ternary operator javascript
javascript ternary
javascript ternary operator
tertiary javascript
ternary javascript
js ternary