Functions return and Ternary Operator

Hi guys,

I am a bit confused why I can use return in the if…else condition but when I use return on ternary Operator, I get an error?
I have really appreciated it if someone could explain to me why I cannot use return in Ternary operator.

Thank you

const addTwo = num => {
  return num + 2;
}
const checkConsistentOutput = (func, val) => {
  let checkA = val + 2
  let checkB = func(val)

// This works just fine
if ( checkA === checkB ) {
    return checkB
  }
  else {
    return "inconsistent results"
  }
// problem is here when I try writing return in ternary operator
checkA === checkB ? return checkB : return "inconsistent results";

// Instead I have to use this 
const result = checkA === checkB ?  checkB : "inconsistent results";
return result
}

How come I cannot use return in Ternary Operator?

[codebyte]

The return keyword needs to be first:
return checkA === checkB ? checkB : "inconsistent results";

1 Like

Ah yeah, that’s the other way to do it but how come

if ( checkA === checkB ) {
    return checkB
  }
  else {
    return "inconsistent results"
  }

This was ok?

I think you can consider the ternary operator as one expression while you have two separate scopes with the classic if/else statement.

1 Like

Ah that explained it, thank you

Ok, I also found the answer from Stackoverflow.

The ternary operator evaluates to an expression and expressions can’t contain a return statement (how would that behave if you were to assign the expression to a variable?). However, you could very well return the result of a ternary operator, i.e. return condition? returnValue1 : returnValue2;

1 Like