Skip to content

Check if variable is Array JavaScript | Example code

  • by

You can use the isArray method or instanceof operator or constructor type to Check if the variable is Array in JavaScript. The best solution is the one you have chosen.

variable.constructor === Array

This is the fastest method on Chrome, and most likely all other browsers. All arrays are objects, so checking the constructor property is a fast process for JavaScript engines.

Check if variable is Array JavaScript

Simple example code Array.isArray() method checks whether the passed variable is an Array object.

<!DOCTYPE html>
<html>
<body>

  <script>
    let arr = [10, 20, 30, 40];
    var res  = Array.isArray(arr);

    console.log(res)
    console.log(arr)

  </script>

</body>
</html> 

Output:

Check if variable is Array JavaScript

Using the instanceof operator

<script>
    let data = [10, 20, 30, 40];
    var res  = data instanceof Array;
    console.log(res)

</script>

Output: true

Checking the constructor property of the variable

<script>
    let data = [10, 20, 30, 40];
    var res  = data.constructor === Array
    console.log(res)
</script>

Output: true

Do comment if you have any doubts or suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.