How to check object is an array in JavaScript ?
Last Updated :
25 Jul, 2023
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
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();
|
Example 2: This example uses Array.isArray() function to check the object is array or not.
Javascript
function checkObject() {
console.log( Array.isArray(
'hello GeeksForGeeks' )
);
}
checkObject();
|
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
Share your thoughts in the comments
Please Login to comment...