0

Is there a way to execute the following code, without specifying 'a' twice?

const result = a > b ? a : default;

Useful for when the ternary is inside an arrow function and 'a' is an arithmetic operation the uses the function parameters:

someFunc((value) => value + otherValue / 10 > b ? value + otherValue / 10 : default)

Remember that 'a' can be a highly complex calculated expression.

The only way I know to write value + otherValue / 10 once is as follows:

someFunc((value) => {
  const result = value + otherValue / 10;
  return result > b ? result : default;
});

I'm looking for something like: const result = a ?? > b : default;

PS. I know there's nothing wrong with the last example, just asking to figure out if JavaScript has a better way of doing this.

Itiel Maimon
  • 834
  • 2
  • 9
  • 26
  • 4
    What's wrong with the latter example? You don't have to minify your developement code, a minifier will do it for you when you're moving the code to the production. – Teemu Apr 05 '21 at 16:43
  • Use an IIFE, something like: `result = ( value => condition(value) ? value : defaultValue )()`. Although, that's easily extractable to a generic function, so you don't even have to have it inline. In which case you don't have much need for shorter syntax. – VLAZ Apr 05 '21 at 16:45
  • 5
    Stop worrying about how many character your code takes. Worry about whether people who have to maintain your code later will understand it. – Heretic Monkey Apr 05 '21 at 16:46
  • @Teemu Nothing wrong with the latter example. But you can say the same thing about the ternary operation as well. – Itiel Maimon Apr 05 '21 at 16:56
  • 1
    What ever else you put in that ternary, it only obscures your intention. Like Heretic Monkey said, readability is the number one to concern when you're writing code. – Teemu Apr 05 '21 at 16:59

1 Answers1

0

Unfortunately there is no such functionality in JavaScript. You can do this if you need to check the truthiness of the variable. For example a || default so if a is truthy it will be returned otherwise default. But in your case you need to make a comparison of a > b and for the you can only use Ternary expression with re-specifying a.

Evgeny Klimenchenko
  • 1,184
  • 1
  • 6
  • 15