TechNobo
TechNobo

Reputation: 13

Defining and using function in if condition

I need an if statement, where the condition depends on a try-catch succeeding. Defining a new function just to call it once is wasted space, and I'd much rather figure out a one-liner.

I can't use if (try{return true;}catch{return false;}) as it results in a SyntaxError. So take "return false" as a 'failed try-catch attempt'.

This is as short as I could make it where it still works.

// [WORKING] False as expected
if ((() => {return false})()){
    console.log("Condition is true");   
}
else{console.log("Condition is false");}

This makes sense to me, but I don't think it's the most "official" way of doing this. Is this way a good solution? Is there a better way?

Reason this makes sense to me is because I'm checking if the variable exists, is of type number and is bigger than 0.

if ((() => {try{return price > 0}catch{return false}})())

Upvotes: 0

Views: 223

Answers (1)

Scott Sauyet
Scott Sauyet

Reputation: 50787

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.

Upvotes: 2

Related Questions