How do I check if a variable is an array in JavaScript without using Array.isArray()?Antek N
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 theObject.prototype.toString.call()
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:
1 2 3 4 5 6 7 8 9
const variable = [1, 2, 3]; // Variable to check const typeString = Object.prototype.toString.call(variable); // 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.
Similar Questions
How do I check if an object is an array in JavaScript without using Array.isArray()?
How do I check if a variable is an integer in JavaScript without using Number.isInteger()?
How do I check if a value is an integer in JavaScript without using Math.floor()?
How do I check if a value is an empty string in JavaScript without using length?
How do I check if a variable is a string in JavaScript?
How do I check if a variable is an object in JavaScript?
How do I check if a value is an empty object in JavaScript without using Object.keys()?
How do I check if an array is equal to another array in JavaScript?
How do I check if a value is an empty array in JavaScript?
How do I check if a value is an empty array in JavaScript?
How can I check if a value is an array in JavaScript?
How can I check if a value is an array in JavaScript?
How do I check if an object is an array in JavaScript?
How do I check if an object is an array in JavaScript?
How do I check if an element is visible using JavaScript without jQuery?
How do I check if an element exists in an array in JavaScript?
How do I check if an array is empty in JavaScript?
How do I check if an array is empty in JavaScript?