Search code examples
javascriptoptimizationlanguage-theory

Should object properties be declared in javascript?


In a JS function, I'll be using an object resultModel, with two properties idArray and nameArray. What would be the proper way to declare this?

Currently I declare the object with var resultModel together with other variables at the top of the function, but the properties I simply start using by assigning them a value in a loop later in the function:

   resultModel.idArray.push(someValue[i][0]);
   resultModel.nameArray.push(someValue[i][1]);

Of course, I know that the var keyword is important for scoping, and as the "root" identifier is declared in the function I avoid any global tampering and this is all good. But I have an expectation that the properties of the value really should also be declared somehow, for other reasons than scoping - memory allocation springs to mind, possibly type hinting via JSDoc comments, readability and sheer completeness of declaration.

So, my question is: should I declare such properties, and what would in that case be the proper way to do that?


Solution

  • Like this:

    var resultModel = {
        idArray: [],
        nameArray: []
    };
    

    Assignment is considerably slower than just putting the properties on the object in the first place, so this is the best way to go.