An Array Or Not An Array; That Is The Question!

James Hill
James Hill
Published in
2 min readNov 7, 2016

Static type checking is a big loss for me, having moved over to Javascript. But not completely — it’s a double edged sword. Javascript’s deficiencies ironically, can also be it’s strengths!

With concrete type checked languages such as Java, being able to overload functions, for different purposes is invaluable.

And with Javascript, it’s easy to achieve the same. Although additional logic is often required to deal with checking the type of the passed in arguments.

Which leads me onto the purpose of this post, checking if an argument is an Array, and if not making it an Array.

There seem myriad ways of doing this, some efficient, some not.

Array.isArray(arr)

Using Array’s native method isArray, is an obvious choice, when used in a ternary expression, but is a little terse.

var array = Array.isArray(arg) ? arg : [arg];

(arg instanceof Array)

Otherwise, `instanceof’ can achieve the same result, but again, we have to relie on a long winded ternary expression:

var array = arg instanceof Array ? arg : [arg];

‘[object Array]’

Or if we’re just being ridiculous:

var array = Object.prototype.toString.call(arg) == '[object Array]' ? arg : [arg]

And the winner is ..

But I think the winner for me, both aesthetically and conceptually, is the following:

var array = [].concat(arg);

If arg is an Array, it’s values are inserted into the new Array.

var array = [].concat([1,2,3])  
console.log(array.toString()); // 1, 2, 3

If arg isn’t an Array, it’s inserted defacto into the new Array.

var array = [].concat(1);  
console.log(array.toString()) // 1

Short and concise.

--

--