Checking if an object is an array
suggest changeArray.isArray(obj) returns true if the object is an Array, otherwise false.
Array.isArray([]) // true
Array.isArray([1, 2, 3]) // true
Array.isArray({}) // false
Array.isArray(1) // false
In most cases you can instanceof to check if an object is an Array.
[] instanceof Array; // true
{} instanceof Array; // false
Array.isArray has an advantage over instanceof. It still returns true if the array's prototype has been changed, and false if some other object's prototype was set to Array.prototype. It also returns true for an array from another realm, such as an iframe, where instanceof Array is false.
const arr = [];
Object.setPrototypeOf(arr, null);
Array.isArray(arr); // true
arr instanceof Array; // false
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents