Skip to content
the poor coder

How can I check if an object is an array

Poor Man
Published
Reading time
1 min read
On this page

How to Check if an Object is an Array in JavaScript#

If you are working with JavaScript, you might need to check if a variable is an array or not. This can be done using several methods. Here's how:

Method 1: Using instanceof operator#

The easiest way to determine if an object is an array is by using the instanceof operator.

Text

    var arr = [1,2,3];
    if(arr instanceof Array) {
      console.log("arr is an array");
    }
  

Method 2: Using Array.isArray() method#

An alternative method to check if an object is an array is to use the Array.isArray() method.

Text

    var arr = [1,2,3];
    if(Array.isArray(arr)) {
      console.log("arr is an array");
    }
  

Method 3: Using Object.prototype.toString.call() method#

The third method is to use the Object.prototype.toString.call(). This method returns a string representation of the object's type, which can be used to check if it's an array.

Text

    var arr = [1,2,3];
    if(Object.prototype.toString.call(arr) === '[object Array]') {
      console.log("arr is an array");
    }
  

Using any of these methods, you can easily determine if an object is an array or not.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC