Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript argument with multiple data types allowed: good practice or not?

Many times I have seen - especially in jQuery - that a function can have multiple valid data types, let's say either a string or a function. Also, in my own code I sometimes have functions which can take one or several values. So I could call the function with:

myFunc("arg"); or myFunc(["arg1", "arg2", ...]);

This appears to be more flexible and also more convenient to type, but is this actually a good thing?

Because on the other hand, it is not explicitly stated what type the function is, and AFAIK then the JIT compiler cannot work as efficently. And often there has to be a type coercion of some type then, which can introduce an additional performance penalty.

So, would it be better to always write: myFunc(["arg"]) even if there is only one object in the array? What's your take on this?

like image 428
frontend_dev Avatar asked Nov 02 '12 14:11

frontend_dev


1 Answers

JavaScript is loosely typed. This can bite you if you're not careful, but it also provides great flexibility to do things precisely like this. I take advantage of this behavior often; in the function, you'll generally want to have a structure like this:

var func = function(someArg) {
    var data;

    switch (typeof someArg) {
        case 'string':
            // transform someArg into data
            // example: pass it as a jquery selector to get a jquery object
            break;
        case 'object':
            // transform someArg into data
            break;
        ...
        default:
            throw new Error('Invalid argument type passed to func!');
    }

    // rest of function that expects data to be a certain type
};

Your functions will become more flexible and easier to consume at the cost of becoming more complex. Whether the exchange of complexity for flexibility is worth it will vary from situation to situation (and person to person).

Edit: be careful with Array: typeof someArray will give "object", you'd need to use this instead: someArray instanceof Array http://jsfiddle.net/8ycFb/

like image 60
jbabey Avatar answered Oct 19 '22 15:10

jbabey