Javascript : Check if an object is array

While working in javascript arrays, we sometimes encounter a requirement to check if an object is an array. This article demonstrates easy ways to check if a javascript object is an array using different methods and example illustrations.

Table of Contents:

Check if an object is an array using Array.isArray()

Javascript’s Array.isArray() method finds out whether the passed value is an array.

Example:-

Check if the objects myObj1 and myObj2 are arrays or not.

Code:-

function checkIfArray(_object)
{
    if(Array.isArray(_object))
        {
        return true;
        }
    else
        {
        return false;
        }
}    
//usage
let myObj1 = ["Javascript", "Is", "Popular","Language"];
let myObj2 = "Javascript";
console.log(checkIfArray(myObj1));
console.log(checkIfArray(myObj2));

Output:-

true
false

Check if an object is an array using Object.prototype.toString

Javascript’s toString() method will return a string representing the object.

Example:-

Check if the objects myObj1 and myObj2 are arrays or not.

Code:-

function checkIfArray(_object)
{
    if(Object.prototype.toString.call(_object) === '[object Array]') 
        {
        return true;
        }
    else
        {return false;
        }
}
//usage
let myObj1 = ["Javascript", "Is", "Popular","Language"];
let myObj2 = "Javascript";
console.log(checkIfArray(myObj1));
console.log(checkIfArray(myObj2));

Output:-

true
false

Check if an object is an array using constructor.name

Example:-

Check if the objects myObj1 and myObj2 are arrays or not.

Code:-

function checkIfArray(_object)
{
    if(_object.constructor.name == "Array")
        {
        return true;
        }
    else
        {
         return false;
        }
}
//usage
let myObj1 = ["Javascript", "Is", "Popular","Language"];
let myObj2 = "Javascript";
console.log(checkIfArray(myObj1));
console.log(checkIfArray(myObj2));

Output:-

true
false

Check if an object is an array using instanceof

Javascript’s instanceof operator is also to check if a variable belongs to a particular type of object.

Example:-

Check if the objects myObj1 and myObj2 are arrays or not.

Code:-

function checkIfArray(_object)
{
        if(_object instanceof Array)
        {
        return true;
        }
        else
        {
            return false;
        }
}
//usage
let myObj1 = ["Javascript", "Is", "Popular","Language"];
let myObj2 = "Javascript";
console.log(checkIfArray(myObj1));
console.log(checkIfArray(myObj2));

Output:-

true
false

Read More:

I hope this article helped you to check if a particular object is an array in javascript. Good Luck !!!

Advertisements

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top