Search code examples
javascriptobjectinitialization

How to call multiple statements when setting a value for an object property in an object initializer in JavaScript?


If the property to be calculated only requires one statement, it is pretty simple

let object = {
    array: new Array(10)
};

Alternatively I can also do the following (though I don't like it as much)

let object = {};
object.array = new Array(10);

But what if I want to (e.g.) initialize the array with values of 0 (by deafult the values are "undefined")? I can only do it the second way

let object = {};
object.array = new Array(10);
for(let element of array){
    element = 0;
}

The closest thing to the first method that comes to mind might be doing something like this

let object = {
    array: (function(){
        let array = new Array(10);
        for(let element of array){
            element = 0;
        }
        return array;
    })()
}

Maybe there is a simpler way to do this that I do not know of?

Edit: The array was just the first thing that came to mind when thinking of an example. My problem does not lie exclusively on initializing an array, I am looking for a more general solution than using Array.fill().


Solution

  • You can use an IIFE to perform more complex inline calculation of property values from within an object initializer. As an example based on the posted code:

    const obj = {
        array: (()=> { // example code
            const a = new Array(10);
            return a.fill(0);
         })(),
        hw: "hello world",
    }
    
    console.log(obj.hw, obj.array);