Optionally accept an array on a JavaScript function

Let’s say that you want to write a JavaScript function that accepts multiple arguments, and one of them can optionally be an array. You want to run some code against each value in the array — for this example, I’ll just say that we’re going to console.log each item. The ugly way to do this, which I wouldn’t recommend, is:

// The ugly way

function example(possibleArray) {
if (Array.isArray(possibleArray)) {
possibleArray.map(item => console.log(item))
} else {

But we can do better than that. Let’s transform our argument into an array. That way, we don’t need to worry about this ugly conditional statement. We can do this with [].concat. I think it’s better explained in action:

[].concat("Din") // ["Din"]
[].concat(["Nayru", "Farore"]) // ["Nayru", "Farore"]

If our argument is always added to an array, we don’t need to worry about performing the conditional check! So we can condense the 5 lines from the original example into 1:

// The clean way

function example(possibleArray) {
[].concat(possibleArray).map(item => console.log(item))

I'm Mark Thomas Miller, an engineer, designer, and maker of things.