How to Check If Object is an Array in JavaScript

Answer: Use the Array.isArray() Method

JavaScript  Array.isArray()  can be used to determine if an object (or variable) is an array. If the value is an array, this method returns true . Otherwise, it returns false.

Let’s take a look at the following illustration to see 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>

All major browsers support the  Array.isArray()  method, including Chrome, Firefox, IE (9+), and others. To learn more about JavaScript arrays, see the tutorial.

Exit mobile version