'Result of function, as value in object

Is possible to obtain in sum result of a function ? Not function itself, just result.

let a = 1;
let b = 2;

let object = {
    dummy: 'dummy text',
    sum: function () {
        a + b
    },
}

console.log(object) // { dummy: 'dummy text', sum: [Function: sum] }

I want to obtain : { dummy: 'dummy text', sum: 3 } I don't want to use an external function



Solution 1:[1]

Use an IIFE if you want to assign the result of a function invocation to sum

let a = 1;
let b = 2;

let object = {
  dummy: 'dummy text',
  sum: (function () {
    return a + b;
  })(),
};

console.log(object);

Solution 2:[2]

If you want a simple static value, you could simply assign a + b as the value for sum. Otherwise you'd need to invoke sum method call.

let a = 1;
let b = 2;

let object = {
    dummy: 'dummy text',
    sum: a + b,
}

console.log(object) // { dummy: 'dummy text', sum: 3 }

Solution 3:[3]

You just need to execute the function instead of initializing it.

This can be done by instantiating the function before and then call it when creating the object.

let a = 1;
let b = 2;

const sum = (a, b) => a + b

let object = {
    dummy: 'dummy text',
    sum: sum(a, b)
}

console.log(object)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yousaf
Solution 2 Bumhan Yu
Solution 3 RenaudC5