How do I check if a variable is an array in JavaScript without using Array.isArray()?
Antek N
antek n profile pic

To check if a variable is an array in JavaScript without using theArray.isArray() method, you can use theObject.prototype.toString method and compare the result to the string representation of an array. Here's a long-form approach to achieve this: 1. Get the string representation of the variable's type: - Use method and pass the variable as an argument to obtain the internal[[Class]] property of the variable. - This method returns a string in the format"[object Type]", whereType represents the internal class of the object. 2. Compare the string representation to the array's string representation: - Check if the obtained string representation matches the string representation of an array:"[object Array]". - If the strings match, it indicates that the variable is an array. 3. Example:


   const variable = [1, 2, 3]; // Variable to check

   const typeString =; // Get the string representation

   const isArray = typeString === "[object Array]"; // Compare with array's string representation

   console.log(isArray); // Output: true

In this example, thetypeString variable will be set to"[object Array]" becausevariable is an array. The comparisontypeString === "[object Array]" will evaluate totrue, indicating that the variable is indeed an array. Note: While this approach can be used to check if a variable is an array, it's important to mention thatArray.isArray() is the recommended and more reliable way to perform this check. It's widely supported and specifically designed for this purpose.