Check whether a given value is an array before subjecting it to array methods.

Loose typing can be a pain when your methods are being called from other methods / external modules. It is a good idea to check for valid types to avoid throwing runtime errors that are difficult to understand or parse.

Using type checks is one such practice. As seen earlier, type checks is easily done for primitives.

const input = "abc";

console.log(typeof input);
// string

So, how about an array?

const input = [1, 2, 3];

console.log(typeof input);
// object

All complex types return ‘object’, which may or may not be useful depending on what you are doing with that.

If we are doing array operations on an object, we would very much like an array in the input. We can do two things to validate -

Option 1: Use isArray()

Use Array prototype method to check whether a given input is indeed an array.

console.log(Array.isArray([1, 2, 3]));
// true

console.log(Array.isArray({ a: 1 }));
// false

Option 2: Use Object Prototype

function isArray(checkObj) {
  return Object.prototype.toString.call(checkObj) === "[object Array]";
}

Validate whether our code works -

const input = [1, 2, 3];

console.log(isArray(input));
// true

console.log(isArray({ a: 1 }));
// false

You can make this code reusable for different types of objects with a simple change -

console.log(Object.prototype.toString.call([1, 2, 3]));
// [object Array]

console.log(Object.prototype.toString.call({ a: 1 }));
// [object Object]