DEV Community

Discussion on: JavaScript - Ternary Operator

peerreynders profile image
peerreynders • Edited

Doesn't it seem that it's an alternative or rapid way of representing the IF statement?🤔

Strictly speaking no given that a conditional operator is part of an expression - while if is a statement:

  • the if statement conditionally executes a block of statements (or a single statement) - it does not return a value
  • the conditional operator has to return a value - so there always has to be an expression used for a "truthy" condition and another for a "falsy" condition - it's impossible to formulate a valid conditional operator without an else value - something that is fairly standard with an if statement.

Expressions versus statements in JavaScript

an if statement cannot become the argument of a function.

Knowing that you'd likely write your example as:

const status = 'online';

console.log(status === 'online' ? 'ONLINE' : 'OFFLINE');
Enter fullscreen mode Exit fullscreen mode

i.e. using the conditional operator to select the value to pass to console.log() rather than having it evaluate a void function.

Thread Thread
cesar_code profile image
César Author

Thank you for the article. It's interesting! Appreciated🙏.