There is two ways to figure out if an array is an array or an object. Using typeof item === "object";
will return true for an object and an array since arrays are relatively new to javascript and arrays are prototypes of objects(may have worded this wrong, feel free to correct me). So the two ways I know of to determine if an Array is an Array are:
Solution 1:
Array.isArray(item);
Solution 2:
item instanceof Array;
My questions are:
- What is the difference between these two solutions?
- Which of these two is the preferred solution?
- Which has a faster process time?
isArray
is more generic. It works across iframes, whichisntanceof
does not. It also looks like thatisArray
will correctly recognize typed arrays in ES6.instanceof Array
, because: 1. the syntax is consistent withinstanceof (other classes)
, 2. for my Node.js,Array
s and instances extendingArray
are constructed by the sameArray
in the same execution context.isArray
will correctly recognize typed arrays,” but on my Chrome 107,Array.isArray(new Uint8Array)
isfalse
.