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()
- Check if an object is an array using Object.prototype.toString
- Check if an object is an array using constructor.name
- Check if an object is an array using instanceof
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.
Frequently Asked:
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:
- Javascript: Insert an item to array at specific index
- Javascript: Check if an array is empty
- Javascript: Convert array to string (4 ways)
I hope this article helped you to check if a particular object is an array in javascript. Good Luck !!!