Wednesday, February 19, 2025

JavaScript, Check Array Type in JS

Explain Array.isArray() in JS by examples.
Answer: In JavaScript, 'Array.isArray()' is a built-in method used to determine whether a given value is an array. It returns 'true' if the value is an array and 'false' otherwise. Here are a few examples to illustrate its usage:
1. Basic Usage:

Array.isArray([]); // true
Array.isArray([1, 2, 3]); // true
Array.isArray(new Array()); // true

2. Non-Array Values:

Array.isArray({}); // false
Array.isArray(null); // false
Array.isArray(undefined); // false
Array.isArray(123); // false
Array.isArray('Array'); // false

3. Array-like Objects:

function isArrayLike(obj) {
// Example of a function to check if an object is array-like
return typeof obj.length === 'number' && obj.length >= 0;
}
Array.isArray(document.getElementsByTagName('div')); // false (returns NodeList)
isArrayLike(document.getElementsByTagName('div')); // true

4. Edge Cases:

Array.isArray(); // false
Array.isArray([]); // true
Array.isArray(new Array()); // true

The method is useful for type checking in situations where you need to differentiate arrays from other types of objects or values.

No comments:

Post a Comment

Hot Topics