QUESTION
Is there a way to execute a return
statement inside of a ternary operator?
It's a weird thing, because I feel like a ternary is like a shorthand for an if/else, and you CAN execute a return
statement inside an if/else.
But for some reason, I'm not able to execute a return
statement inside of a ternary operator:
Regular IF/ELSE:
// THIS WORKS
function foo() {
if (true) {
console.log('This is true');
} else {
console.log('Not true');
}
}
TERNARY as IF/ELSE:
// THIS ALSO WORKS
function bar() {
true ?
console.log('This is true')
: console.log('Not true');
}
Both codes above works just fine. But when return is involved, the following happens:
Regular IF/ELSE with return:
// THIS WORKS
function foo() {
if (true) {
console.log('This is true');
} else {
return;
}
}
TERNARY as IF/ELSE with return:
// THIS DOESN'T WORK
function bar() {
true ?
console.log('This is true')
: return;
}
CONCERNING POSSIBLE DUPLICATES:
I have looked around and didn't find an answer to this exact question.
It's clear to me that I can return a ternary operator, like the following piece of code, but this is not what this question is about.
function foo() {
return(
true ?
console.log('This is true')
: null
);
}