Can we use Ternary Operator inside JavaScript Functions?

I’m trying to run this code, and it’s returning me undefined. I’m using Ternary Operator inside a function.

function meetsSpeedRangeRequirements(maxSpeed, minSpeed, requiredSpeedRange) {
  const range = maxSpeed - minSpeed;
  range > requiredSpeedRange ? true : false;
};

console.log(meetsSpeedRangeRequirements(650, 250, 600));

Can we use Ternary operator inside functions ? if so is that a good practice ?

Thanks

because the return keyword is missing?

yes

when used correctly, sure. But that is not the case here. A comparison itself already returns a boolean value:

console.log(typeof (5 === 5))

so the ternary operator is redundant.

1 Like

Thanks. I tried three different flavors

  1. with return statement, but this didn’t work and was getting syntax error of ‘unexpected token’
function meetsSpeedRangeRequirements(maxSpeed, minSpeed, requiredSpeedRange) {
  const range = maxSpeed - minSpeed;
  range > requiredSpeedRange ? return true : return false;
};

console.log(meetsSpeedRangeRequirements(650, 250, 600));
  1. Tried with console.log, which worked and returned correct result:
function meetsSpeedRangeRequirements(maxSpeed, minSpeed, requiredSpeedRange) {
  const range = maxSpeed - minSpeed;
  range > requiredSpeedRange ? console.log(true) : console.log(false);
};

meetsSpeedRangeRequirements(650, 250, 600);
  1. As suggested by you, Ternary Operator is redundant in this case, so I tried without it, returned correct result.
function meetsSpeedRangeRequirements(maxSpeed, minSpeed, requiredSpeedRange) {
  const range = maxSpeed - minSpeed;
  return range > requiredSpeedRange;
};

console.log(meetsSpeedRangeRequirements(650, 250, 600));

no, the correct result is logged, not returned.

the syntax for ternary operator is different, it is:

return condition ? true : false

unlike a regular if/else where you have to repeat the console.log() or return, that is not needed when using ternary operator.

Cool, thanks for pointing the right direction! :slight_smile:

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.