Skip to content

JavaScript instanceof Array | Example code

  • by

JavaScript instanceof Array evaluates to false when the value is an array created in a different frame than the Array constructor function. There are some cases where obj instanceof Array can be false, even if obj is an Array.

In modern browsers you can do:

Array.isArray(obj)

You could also try using the instanceof operator

myArray instanceof Array

JavaScript instanceof Array

Simple example code ways to detect an array instance in JavaScript.

Array.isArray(value)

The isArray() utility function returns true if value is an array.

<!DOCTYPE html>
<html>
<body>

  <script>
   const array = [1, 2, 3];
   console.log(Array.isArray(array))
 </script>

</body>
</html> 

Output:

JavaScript instanceof Array

However, there’s an important point to consider. While using instanceof works well for native JavaScript objects like arrays, it might not behave as expected if you’re dealing with objects from different contexts, such as iframes or cross-frame communication. In such cases, it’s recommended to use other methods like Array.isArray() to accurately check if an object is an array:

const myArray = [1, 2, 3];

if (Array.isArray(myArray)) {
  console.log('myArray is an array');
} else {
  console.log('myArray is not an array');
}

Array.isArray() is a more reliable method for checking whether an object is an array, regardless of the execution context.

Value instanceof Array

<script>
   const arr = [1, 2, 3];
   console.log(arr instanceof Array)
</script>

Checking the constructor property of the variable

Another method to check a variable is an array by checking its constructor with Array.

<script>

   const arr = [1, 2, 3];
   console.log(arr.constructor === Array)

</script>

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 *