Fill an array of objects with some default object I have an array of objects. Whatever may be the size of this array, I need to ensure the size of the array as n using a default object.

 function fillRemaining(arr, n) {
        var defaultObject = {'id' : 0, 'name' : ''};
        var temp = 0;
        while(arr.length + temp &lt; n ) {
           var template = $.extend({}, defaultObject);
           template.id = new Date().getTime();
           arr.push(defaultObject);
           temp++;
        }
    }


Is there a better method of doing it?
I see a few ways this can be improved.

First, you are creating the template variable as a copy of the defaultObject, but then you are inserting defaultObject rather than template. I am going to assume this is a bug.

I would also say that there is not a big reason why you should have a defaultObject, then create and modify a copy to add. Just create objects on the fly.

Second, you are using a while loop, but constructing it like a for loop (loop variable, incremented every iteration). You actually don't even use the loop variable, so it can be removed completely. There is also a second potential bug where you are checking against arr.length + temp in your conditional, but arr.length increases every time you add an element to the array, so you are counting by 2's instead of by 1's.

Lastly, the name fillRemaining does not clearly describe what the function is supposed to do. Since it is padding onto the end of the array, perhaps padArrayWithDefault or something similar might be more descriptive.

Here's what I would suggest:

function padArrayWithDefault(arr, n) {
    while(arr.length &lt; n) {
        arr.push({
            "id": new Date().getTime(),
            "name": ""
        });
    }
}