Optional array as JavaScript param

Let’s say that you want to write a JavaScript function that accepts multiple arguments, and one of them should can either be an array or… not an array. In other words, your function should support both of these:

example(["din", "nayru", "farore"])

The best way to handle this is by always treating our argument like it’s an array. We can do this with [].concat. I think it’s better explained in action:

[].concat("din") // ["din"]
[].concat(["nayru", "farore"]) // ["nayru", "farore"]

Put together, we end up with something like this:

function example(possibleArray) {
const arguments = [].concat(possibleArray)
// Perform logic against the arguments here.
// For instance, arguments.map(item => ...)

This approach makes for a nice, clean interface that doesn’t dirty your code with unnecessary if statements. If you have any more questions, feel free to reach out to me.