DEV Community

Discussion on: JavaScript Ternary Operator

Collapse
 
peerreynders profile image
peerreynders • Edited

It is valuable to say that this is for one-liners purpose.

That is missing the point.

The value of the conditional operator is that it is an expression, so it can be used anywhere where a value is needed (because expressions always have to evaluate to a value - even if that value is undefined).

if...else is a statement:

const age = 23;
let status = 'You are not adult!';
if(age >= 18) status = 'You are adult!';
Enter fullscreen mode Exit fullscreen mode
  • With if...else the else is entirely optional. With the conditional operator an alternate expression/value has to be supplied.
  • Here status can't be const bound because the if may need to change it.

const still can't be used here:

const age = 23;
let status;
if(age >= 18) status = 'You are adult!';
else status = 'You are not adult!';
Enter fullscreen mode Exit fullscreen mode

Without the conditional operator you have to resort to using functions in order to const bind status:

const age = 23;
const isAdult = () => age >= 18;
const status = myIf(isAdult, makeAdultStatus, makeYouthStatus);

function myIf(conditionFn, trueFn, falseFn) {
  if (conditionFn()) return trueFn();

  return falseFn();
}

function makeAdultStatus() {
  // ... some expensive status generation
  return 'You are an adult!';
}

function makeYouthStatus() {
  // ... some expensive status generation
  return `You aren't an adult!`;
}

console.log(status);
Enter fullscreen mode Exit fullscreen mode

Expressions versus statements in JavaScript

I find that people don't tend to use the conditional operator until they clearly understand the difference between statements and expressions.

a statement is a line of code commanding a task

  • the if statement changes the value that is bound to status
  • the conditional operator produces the new status value based on the existing age value.

That's a different way of thinking - similar to using .map() or .filter() to create a new array from an existing array.

Collapse
 
lorenzojkrl profile image
Lorenzo Zarantonello

Excellent addition!