The Array.isArray() method determines whether the passed value is an Array.
✅ Implementation
function customIsArray(value) { // Return false if the value is null or undefined if (value === null || value === undefined) { return false; } // Use Object.prototype.toString to reliably check the type of value // This method returns '[object Array]' for arrays return Object.prototype.toString.call(value) === '[object Array]'; }
Explanation:
- Null and Undefined Check :
The function first checks if
valueisnullorundefined. If it is, it immediately returnsfalse. - Reliable Type Checking :
For all other values, the function uses
Object.prototype.toString.call(value). This method returns a string in the format"[object Type]", whereTypeis the internal class of the object. For arrays, it returns"[object Array]". - Why This Works :
Object.prototype.toStringis a reliable way to determine the internal class of an object, which helps accurately identify arrays. This is a cross-environment solution that works similarly toArray.isArray().
Behavior:
- Returns
truefor arrays : Works for empty arrays, populated arrays, arrays created with theArrayconstructor, and evenArray.prototype. - Returns
falsefor non-arrays : Includesundefined,null, objects, numbers, strings, booleans, and array-like objects such asTypedArrays.
Quick Quiz
Test your understanding with 3 quick questions
Q1Why is `Object.prototype.toString.call()` used instead of `typeof`?
Q2What does `customIsArray({ length: 3 })` return?
Q3What string does `Object.prototype.toString.call([])` return?