-2

So I tried to change the code below into a ternary operator, but it gave me and undefined result. Please can someone explain to me where I went wrong and how to deal with it appropriately. T for thanks.

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

console.log(plantNeedsWater('Tuesday'));
nkadm
  • 11
  • 2

1 Answers1

0

A function with a simple plain return; returns undefined, not a primitive Boolean.

Also, you don't need a ternary operator, simply return your evaluation

const plantNeedsWater = function (day) {
  return day === 'Wednesday';
}

console.log(plantNeedsWater('Tuesday'));   // false
console.log(plantNeedsWater('Wednesday')); // true

or in an ES5 fashion using Arrow Function with implicit return:

const plantNeedsWater = (day) => day === 'Wednesday';

Otherwise, if you really must use the Conditional (ternary) Operator you could use it to return non-Boolean values:

const plantNeedsWater = function (day) {
  return day === 'Wednesday' ? "yes" : "no";
}

console.log(plantNeedsWater('Tuesday'));   // "no"
console.log(plantNeedsWater('Wednesday')); // "yes"
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313