Q:

How to Check If Object is an Array in JavaScript

0

How to Check If Object is an Array in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the Array.isArray() Method

You can use the JavaScript Array.isArray() method to check whether an object (or a variable) is an array or not. This method returns true if the value is an array; otherwise returns false.

Let's check out the following example to understand how it works:

<script>
    // Creating some variables
    var v1 = {name: "John", age: 18};   
    var v2 = ["red", "green", "blue", "yellow"];
    var v3 = [1, 2, 3, 4, 5];
    var v4 = null;
    
    // Testing the variables data type
    typeof(v1); // Returns: "object"
    typeof(v2); // Returns: "object"
    typeof(v3); // Returns: "object"
    typeof(v3); // Returns: "object"
    
    // Testing if the variable is an array
    Array.isArray(v1);  // Returns: false
    Array.isArray(v2);  // Returns: true
    Array.isArray(v3);  // Returns: true
    Array.isArray(v4);  // Returns: false
</script>

The Array.isArray() method is supported in all major browsers, such as Chrome, Firefox, IE (9 and above), etc.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Remove an Event Handler in jQuery... >>
<< How to Get the data-id Attribute of an Element Usi...