简体   繁体   中英

JavaScript: How can I get and use a value multiple times in an expression

I often find myself in a situation where I have a value followed by an expression that either uses the value multiple times or both uses the expression and returns it. For example:

const errorCode = getErrorCode();
return new Error(`Error ${errorCode}: ${getErrorMessage(errorCode)}`);

const foo = getFoo();
return [getBar(foo), getBaz(foo)];  // Assume that I cannot make a function getBarAndBaz(foo)

const result = getResultOrNull();
return result
  ? result
  : getAlternative();

I would like to be able to avoid assigning the value to a variable so that I can convert these into one liners.

  • Is there a technique or techniques that I can use to accomplish this?
  • Is there a term for what I am trying to do or a name for the technique that other programming languages use to accomplish this?

If I was hypothesizing what syntax for this could look like, I could see it being something like one of the following:

return new Error(`Error ${errorCode}: ${getErrorMessage(errorCode)}`), where errorCode = getErrorCode();

return (getFoo(), getBar()) -> { foo: $1, bar: $2, baz: getBaz($1, $2)};

Both of these ideas seem similar to an immediately invoked function expressions (IIFE) except that the arguments are calculated rather than being passed in. Therefore, I could use an IIFE with either default values or a closure:

(
  (foo = getFoo(), bar = getBar()) => ({ foo, bar, baz: getBaz(foo, bar)})
)()

(
  () => {
    const foo = getFoo();
    const bar = getBar();
    return (
      () => ({ foo, bar, baz: getBaz(foo, bar) })
    )();
  }
)()

However, these both seem a little messy.

I could use a do expression ( https://github.com/tc39/proposal-do-expressions ):

do {
  const foo = getFoo();
  const bar = getBar();
  { foo, bar, baz: getBaz(foo, bar) };
};

However, do expressions are not yet part of JavaScript and it would be nice to find an alternative that is truly a one liner.

Kind of one liner, although ugly of course:

function getFoo() {
  return 'FOO';
}
function getBar() {
  return 'BAR';
}
function getBaz(...args) {
  return args;
}

let result;

if (1) { let foo = getFoo(); let bar = getBar(); result = { foo, bar, baz: getBaz(foo, bar) };}

console.log(result);

// { foo: 'FOO', bar: 'BAR', baz: [ 'FOO', 'BAR' ] }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM