DEV Community

Discussion on: JavaScript - Ternary Operator

Collapse
cesar_code profile image
César Author

I appreciate your feedback.😀

However, I always have to remind myself that this article is intended for beginners who are still struggling with logic etc. Remaining as simple as possible is mandatory.

With that being said, "A ternary operator is a shorthand version of the conditional statement" isn't entirely my own formulation. It's universally recognized as, and I quote from MDN Documentation Conditional Ternary Operator, an operator which is frequently used as a shortcut for the if statement.

Doesn't it seem that it's an alternative or rapid way of representing the IF statement?🤔 This doesn't mean it should replace it altogether.

You might have read it subjectively, but we are all on the same page at the end of the day as your comment repeats what I clarified in the article. But truly appreciated 🙏.

Collapse
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🙏.