Search code examples
javascriptoptimizationtiming

How is better to check parameters object in javascript?


Most of time I use something like this:

function(obj) {
   obj = obj || {};
   // do stuff
   var foo = obj.foo;
}

But my coworkers played a little bit with console.time/timeEnd and ensured me that

if (obj) 
   var foo = obj.foo;

is faster (code may be more complicated, it's only example).

But, as for me, 1st variant looks better. But we created additional empty object every time (when no parameters passed). I would like to hear what do you think guys. What method do you use?


Solution

  • The first method is appropriate when you need a valid object in obj for the rest of your code and you want to assure there is a valid object in just one place in the code.

    The second method is appropriate when you just want to check if obj was passed or not and do something different in your code depending upon that condition. A more robust check would be:

    if (typeof obj === "object")
    

    So, these are different techniques that accomplish different goals and are mostly used in different circumstances.

    So, the answer is that "it depends upon what the rest of your code is doing and on what you're really trying to accomplish in your code". There is no one answer that is always correct.

    A common design pattern for your first technique is used when you have an optional object with optional properties and you want to fill in default values for missing properties or even if the whole object was not passed:

    function doSomething(obj) {
       var defaults = {timeout: 2000, caseSensitive: false, waitTime: 400};
       var options = Object.assign({}, defaults, obj);
    
       // safely use options object in the rest of this function
    }
    

    This technique also safely works on a copy of the passed object so the caller's object is never modified.