Search code examples
javascriptobjectsyntaxdefinition

Is it possible to reference already defined field value during object definition?


const message = {
  from: "abc",
  to: this.from,
}

console.log(message)

The above is extremely simplified version, where from was obtained through expensive asyn function call, and to is actually in form of is_to_exist ? use_to : use_from.

Is it possible to avoid doing the expensive asyn function call to obtain from again in to assignment, and use the already defined from value here?


Solution

  • One alternative is to use a temporary local variable, e.g.

    const from = await someExpensiveFunction();
    
    const message = {
        from,
        to: is_to_exist ? use_to : from,
    };
    
    console.log(message);