Detecting arrays

Detecting arrays in JavaScript is thankfully very straightforward due to the Array.isArray method:

if (Array.isArray(value)) {
// ...
}

What this method tells us is that the passed value was constructed via the array constructor or an array literal. However, it does not check the [[Prototype]] of the value, so it is entirely possible (although unlikely) that the value, although appearing like an array, may not have the characteristics you desire.

When we believe that we need to check whether a value is an array, it's important to ask ourselves what we're really trying to detect. It may be the case that we can check for the characteristics we desire instead of the type itself. It's crucial to consider what we will be doing with the value. If we are intending to loop over it via for...of, then it may be more suitable for us to check for its iterable-ness instead of its array-ness. As we mentioned earlier, we can employ a helper like this to do so:

function isIterable(obj) {
return obj != null &&
typeof obj[Symbol.iterator] === 'function';
}

const foo = [1,2,3];
if (isIterable(foo)) {
for (let f in foo) {
console.log(f);
}
}

// Logs: 1, 2, 3

If, alternatively, we are looking to use specific array methods such as forEach or map, then it's best to check via isArray as this will give us as a reasonable level of confidence that these methods exist:

if (Array.isArray(someValue)) {
// Using Array methods
someValue.forEach(v => {/*...*/});
someValue.sort((a, b) => {/*...*/});
}

If we were inclined to be really thorough, we could also individually check for specific methods, or we could even force the value into an array of our own so that we could operate on it freely while knowing that the value is truly an array:

const myArrayCopy = [...myArray];

Note that copying an array-like value via the spread syntax ([...value]) will only work if the value is iterable. An example of when using [...value] is appropriate is when operating on NodeLists that have been returned from the DOM API:

const arrayOfParagraphElements = [...document.querySelectorAll('p')];

A NodeList is not a true Array, so it does not give us access to native array methods. Due to this, it is useful to create and use a copy of it that is a true Array.

On the whole, it is safe to adopt and rely on Array.isArray, but it's important to consider whether you even need to check for Array, whether it's more appropriate to check for whether the value is iterable, or even whether it has a specific method or property. As with all other checks, we should seek to make it obvious what our intent is. If we're employing checks that are more obscure than Array.isArray, then it may be prudent to add a comment or abstract the operation away with a descriptively named function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.61.170