How to check if an object is an array in JavaScript

October 14, 2022 No comments javascript arrays javascript-objects

Introduction

In JavaScript, there are situations when we need to check if an object is an array. In this article, we'll look at how to do it.

How to check if an object is an array

To check if an object is an array use Array.isArray(obj) function:

const array = ['1', '2', '3', '4'];
const str = 'text';
const num = 123;

console.log(Array.isArray(array)); // true
console.log(Array.isArray(str)); // false
console.log(Array.isArray(num)); // false

Conclusion

In this article, we learned how to check if an object is an array. Luckily in modern browsers we have a dedicated method to do it, but in case our browser doesn't support the Array.isArray(obj) method we could implement that function by ourselves:

if (typeof Array.isArray === 'undefined') {
  Array.isArray = function(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
  }
};
{{ message }}

{{ 'Comments are closed.' | trans }}