Is It an Array? - Javascript Type Checking Challenge
This challenge focuses on accurately determining if a given value is a Javascript array. Understanding how to reliably check data types is crucial for writing robust and predictable code, especially when dealing with user input or data from external sources. Your task is to create a function that definitively identifies whether a provided value is a Javascript array.
Problem Description
You are tasked with creating a Javascript function named isArrayLike that takes a single argument, value, and returns true if value is a Javascript array, and false otherwise. The function should handle various input types and edge cases correctly. It's important to distinguish between arrays and array-like objects (e.g., arguments, NodeList) as well as other data types like objects, strings, numbers, booleans, null, and undefined.
Key Requirements:
- The function must return a boolean value (
trueorfalse). - The function must correctly identify Javascript arrays.
- The function should handle edge cases gracefully (e.g., null, undefined, non-object types).
- The function should not rely solely on
typeof value === 'object'as this will incorrectly identifynullas an object. - The function should correctly identify array-like objects (objects with a
lengthproperty and indexed access) as arrays.
Expected Behavior:
The function should return true for all Javascript arrays, including those created with new Array() and []. It should return false for all other data types, including null, undefined, primitive types (string, number, boolean), and regular objects that are not array-like.
Examples
Example 1:
Input: [1, 2, 3]
Output: true
Explanation: This is a standard Javascript array.
Example 2:
Input: "hello"
Output: false
Explanation: This is a string, not an array.
Example 3:
Input: { 0: 'a', 1: 'b', 2: 'c', length: 3 }
Output: true
Explanation: This is an array-like object (has a length property and indexed access), and should be treated as an array.
Example 4:
Input: null
Output: false
Explanation: Null is not an array.
Example 5:
Input: undefined
Output: false
Explanation: Undefined is not an array.
Example 6:
Input: new Array(3)
Output: true
Explanation: This is an array created using the Array constructor.
Constraints
- The input
valuecan be of any Javascript data type. - The function must be performant; avoid unnecessary iterations or complex operations. A simple and efficient solution is preferred.
- The function should be compatible with all modern Javascript environments.
Notes
Consider using the Array.isArray() method as a starting point, but be aware of its limitations in older environments. Think about how to reliably check for the presence of a length property and indexed access to identify array-like objects. Remember that typeof null returns "object", so a simple typeof check is insufficient.