Ternary operator javascript Code Example

Last Updated On Saturday 4th Dec 2021
	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")