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
}
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;