The problem with if (try {return true;} catch {return false;})
is that you're trying to use return
outside a function; it makes no sense there.
As all the comments pointed out, you can do what your second block suggests, and that's probably the only reasonable way to get this behavior. But, again as the comments note, this makes very little sense. If it's small enough to fit in a one-liner inside a typical if
-condition, then it's probably just a single expression, in which case you might as well just use that expression as your condition.
That is, instead of
if ((() => doSomething('with', 'my data'))()) {
//...
} else
// ...
}
you might as well just write
if (doSomething('with', 'my data')) {
// ...
} else
// ...
}
If it's not a single expression, then it makes much more sense to place it in a named function and call it in your if
-condition.
This imposes no additional penalty. That function, whether in your condition or just outside it, is going to take the same amount of memory; it will be eligible for garbage collection when the current scope ends. (I guess the one inside the condition might be eligible sooner; but I wouldn't count on it; it's certainly not enough to be worth adding complexity to code.)
In other words, this:
const myFunc = (some, args) => {
const step1 = doSomething('with' args);
const step2 = doAnotherThing('with', step1, 'and', some, args);
return doAThirdThing('with', step2)
}
if (myFunc('my', 'data')) {
//...
} else {
// ...
}
is cleaner and much more readable than
if (((some, args) => {
const step1 = doSomething('with' args);
const step2 = doAnotherThing('with', step1, 'and', some, args);
return doAThirdThing('with', step2)
})('my', 'data')) {
//...
} else {
// ...
}
You will thank yourself later for not doing the latter, I promise you.