Computer >> Computer tutorials >  >> Programming >> Javascript

What is the difference between instanceof() and Array.isArray() methods in JavaScript?


Array.isArray() method is universal, it can function any where whereas instanceof operator is not universal, it can't work in new environment..

syntax-1

Array.isArray(array);

syntax-2

array instance of Array;

In the following example, where there is no new environment created, both Array.isArrar() and instanceof have produced same output.

Example

<html>
<body>
<script>
   var a = [1,2,3,4,5];
   document.write(Array.isArray(a));
   document.write("</br>");
   document.write((a instanceof Array));
   document.write("</br>");
   var b = {}
   document.write(Array.isArray(b));
   document.write("</br>");
   document.write((b instanceof Array));
</script>
</body>
</html>

Output

true
true
false
false

Now lets try to create a new environment or a new frame so as to check whether instanceof operator works there or not.

In the following example, a new frame is created using 'iframe'(a frame property which produces an array like object). Later on an array like object is created in that new frame and passed through both the functions. Since instanceof is not universal it takes that the framed array is not an actual array and returned false as output whereas Array.isArray() returned true as shown in the output.

Example

<html>
<body>
<script>
   var iframeE = document.createElement('iframe');
   iframeE.style.display = "none";
   document.body.appendChild(iframeE);
   iframeArray = window.frames[window.frames.length - 1].Array;
   var a = new Array(1,2,3,"hi",4, "hello");
   var b = new iframeArray(1,2,3,4);
   document.write(Array.isArray(a));
   document.write("</br>");
   document.write(a instanceof Array);
   document.write("</br>");
   document.write(Array.isArray(b));
   document.write("</br>");
   document.write(b instanceof Array);
</script>
</body>
</html>

Output

true
true
true
false