This page looks best with JavaScript enabled

Check if type of value is array

 ·   ·  ☕ 2 min read

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.

1
2
3
4
const input = "abc";

console.log(typeof input);
// string

So, how about an array?

1
2
3
4
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.

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

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

Option 2: Use Object Prototype

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

Validate whether our code works -

1
2
3
4
5
6
7
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 -

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

console.log(Object.prototype.toString.call({ a: 1 }));
// [object Object]
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things