Last Updated: February 25, 2016
·
510
· jsantix

Easily deal with mixed object|array parameters

function foo(myMixed)
{
    var myArray = [].concat(myMixed);
    for(var i = myArray.length; i--; ){
        //do your stuff
    }
}

This way you can make calls like: foo('bar') or foo(['bar', 'baz']) without checking if the parameter is or not an Array and then converting it. Just one single line of code needed.

Note: I did never say it is efficient, so don't use it for huge arrays.

Note2: This trick isn't mine, I found it somewhere in StackOverflow, but I wanted to share it.