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 the variable is Array JavaScript

A 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

You can also use the instanceof operator to check if a variable is an array. The instanceof operator tests whether an object has a specific prototype in its prototype chain. Here’s an example of how you can use it to check if a variable is an array:

<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

You can check the constructor property of a variable to determine its type. Here’s an example of how you can check if a variable is an array by examining its constructor property:

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

Output: true

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading