Ternary operator troubleshooting

Why does this code fail? I was trying to use a ternary operator instead of a traditional if/else statement to simplify the code, but it returns with an "unexpected token return error’ after the ?

const plantNeedsWater = function(day) {
  day === 'Wednesday' ? return = true : return = false;
}

plantNeedsWater('Tuesday');

console.log(plantNeedsWater('Tuesday'));
1 Like

you got the syntax for the ternary operator slightly wrong, its:

return condition ? true_value : false_value

or if you want to assign a variable:

let some_variable = condition ? true_value : false_value
return some_variable

This is not uncommon to see, but in this form…

day === 'Wednesday' ? return true : return false;

return is not a variable that can be assigned a value. It is akin to an operator that takes an operand.

While perfectly valid, Python’s syntax permits us to set return at the beginning of the statement, as usual, and let the entire expression be the operand…

    return day === 'Wednesday' ? true : false;

The expression is first evaluated to determine what the actual return value will be, either true or false, and it is that value that is returned.

The same would apply to logging, or as @stetim94 pointed out, assigning. It is typical to see the following,

 day === 'Wednesday' ? console.log(true) : console.log(false);

Again, perfectly valid, but it doesn’t exploit the expression the way this does…

console.log(day === 'Wednesday' ? true : false);

This way the evaluation takes place and only the applicable value is logged.

const isEven = n => n % 2 === 0;

m = 17;
console.log(`${m} is ${isEven(m) ? `Even` : `Not Even`}.`)
// 17 is Not Even.

That last example might not yet have been covered in your lessons, so give it a pass until it does come up. The back tick is a special quote used in JS template literals, and may also be used in all JS strings in place of normal quotes (' ', " "). It permits us to interpolate expressions (${expression}) in the string so that variables and other expressions can be written directly into the string.

Bear in mind that ALL expressions yield a value.

2 Likes