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

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

Tags:

Leave a Reply

Your email address will not be published.

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