Checking If an Object Is an Array in Javascript

In JavaScript, you can check if an object is an array using the Array.isArray() method. This method returns true if the provided value is an array, and false otherwise.

Array.isArray() Method:
  • Purpose: To determine whether a given value is an array.
  • Syntax: Array.isArray(value)
  • Return Value:
    • true if the value is an array.
    • false if the value is not an array.
Key Points:
  • Use Array.isArray() to ensure accurate array detection.
  • It's simple, readable, and consistent.
  • Avoid using typeof or instanceof for this purpose, as they can have edge cases.
  • Array.isArray() is the preferred method for checking array types in JavaScript.

 
const animals = ['lion', 'elephant', 'giraffe'];
 
if (Array.isArray(animals)) {
    console.log('animals is an array');
} else {
    console.log('animals is not an array');
}
 
 

In this example, the Array.isArray(animals) statement checks if the animals variable is an array. Since animals is indeed an array, the condition is true, and the message "animals is an array" will be logged to the console.

Companies Array with Objects

 
let companies = [
  { name: "Google", industry: "Technology" },
  { name: "Apple", industry: "Technology" }
];
console.log(Array.isArray(companies));   // Output: true
 
 

companies is an array, even though it contains objects as elements.

Checking for an instance of the Array object

 
const exampleArray = new Array(1, 2, 3);
 
if (Array.isArray(exampleArray)) {
  console.log('exampleArray is an instance of the Array object');
} else {
  console.log('exampleArray is not an instance of the Array object');
}
 
 

In this example, exampleArray is created using the Array constructor. The Array.isArray(exampleArray) condition evaluates to true, indicating that exampleArray is an instance of the Array object.