BY Akash Kava18 Oct 2021 Edit
Difference between `instanceOf Array` and `Array.isArray`

There are two major differences between instanceOf Array and Array.isArray

Cross Context Object

In browser, when you access object from different window (such as different iframe from same domain), instanceOf Array will return false. However Array.isArray will return true.

For example,

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iArray = window.frames[window.frames.length-1].Array;
var arr = new iArray(1,2,3); // [1,2,3]

// Correctly checking for Array
Array.isArray(arr);  // true
// Considered harmful, because doesn't work through iframes
arr instanceof Array; // false

Why?

Well internally, all root level (global) functions/constructors such as Array, Object are isolated under the currently executing contexts. Two browser windows or two iframes will have different context and object created in one context will have prototype associated with the context.

When object is accessed in different context, instanceOf will fail to identify object's prototype chain in current context.

Created with Object.create

var a = Object.create( Array.prototype, {});
a.push(1);
a.push(2);

var b = [];
b.push(1);
b.push(2);
console.log(a.join()); // it will display '1,2'.
console.log(b.join()); // it will display '1,2'.

Array.isArray(a); // false
Array.isArray(b); // true

a instanceOf Array; // true
b instanceOf Array; // true

Why?

With Object.create, Array.prototype is present in prototype chain of a, so instanceOf Array will be true, as in the context of JavaScript, a has prototype of Array. So all the methods of Array will work correctly on a as those methdos are generic.

But Array.isArray does not check for prototype, it checks if it was created using Array constructor, which internally is a separate type of object in the language it was implemented. Such as in V8, Array constructor will create an object of class V8Array which inherits V8Object. And Object.create will create V8Object. Array.isArray method in V8 will check if the receiver is instance of V8Array class in C++. Similarly every JavaScript engine will check natively, what kind of object it is, rather then checking prototype.

BY Akash Kava
1 Like
LikeCommentSave
LikeCommentSaveShare
1
Categories
General
YantraJS
Developer Guides
Tutorials
Web Atoms Updates

POPULAR POSTS
17 Mar 2021
LATEST ACTIVITY
shubham.neurospeech
liked this post.
Simmi Kava
liked this post.
Show more
ARCHIVES
2021
2020
2019
2018
TAGS
javascript (46)
developer (25)
javascriptdeveloper (15)
Xamarin.Forms (15)
coding (10)
webatoms (10)
xamarin (10)
android (8)
arrays (8)
typescript (8)
csharp (6)
dotnet (5)
function (5)
iOS (5)
update (5)
web-atoms (5)
dotnet-standard (4)
methods (4)
object (4)
xamarin.android (4)
xamarin.io (4)




Web Atoms: JSX (TSX + TypeScript) for Xamarin.Forms, Hot Reload Your App in Production Environment

PlaygroundSamples Repository