Open In App

How to check object is an array in JavaScript ?

Last Updated : 25 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to check whether the given object is an array or not in JavaScript. There are two approaches, these are:

  • Using Array.isArray() Method
  • Using typeof Operator

Approach 1: Using Array.isArray() Method

The Array.isArray() method determines whether the value passed to this function is an array or not. This method returns true if the argument passed is an array else it returns false.

 Syntax:

Array.isArray( obj )

Parameter:

  •  obj is any valid object in JavaScript like map, list, array, string, etc. 

Return Value: It returns Boolean value true if the object passed is an array or false if the object passed is not an array. 

Example 1: This example uses Array.isArray() method to check the object is array or not. 

Javascript




function checkObject() {
    const countries = ["India", "USA", "Canada"];
    const checkArrayObj = Array.isArray(countries);
 
    console.log(checkArrayObj);
}
 
checkObject();


Output

true

Example 2: This example uses Array.isArray() function to check the object is array or not. 

Javascript




function checkObject() {
         
    // It returns false as the object
    // passed is String not an array
    console.log( Array.isArray(
        'hello GeeksForGeeks' )
    );
}
 
checkObject();


Output

false

Approach 2: Using typeof Operator

In JavaScript, the typeof operator returns the data type of its operand in the form of a string where an operand can be any object, function or variable. However, the problem with this is that it isn’t applicable for determining array. 

Syntax:

typeof operand or typeof( operand )

Example: 

Javascript




console.log(
    typeof "Geeks" + "\n" +
    typeof [1, 2, 3, 4] + "\n" +
    typeof {name:'Kartik', age:20} + "\n" +
    typeof new Date() + "\n" +
    typeof function () {} + "\n" +
    typeof job + "\n" +
    typeof null
);


Output

string
object
object
object
function
undefined
object



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads