JavaScript · Question 82
Why can instanceof fail for objects created in another browser realm, and why is Array.isArray() safer for arrays?
Direct answer
instanceof normally checks an object against a constructor’s prototype relationship, so an array created by another realm has that realm’s Array.prototype; Array.isArray() performs an array-specific brand check and works across realms.
An iframe has its own global object and its own intrinsic constructors. If an array comes from that iframe, then foreignArray instanceof window.Array can be false because the foreign array’s prototype chain contains the iframe’s Array.prototype, not the current window’s one.
By contrast, Array.isArray(foreignArray) is designed to answer whether the value is an actual Array regardless of which realm created it. This distinction matters in libraries that communicate across iframes or other realm boundaries.
- Do not use
instanceof Arrayas the strongest cross-realm array test. - The same general realm issue can affect assumptions involving other built-in constructors and prototype identity.
instanceofcan also be customized throughSymbol.hasInstance, so it is not universally equivalent to “was created by this exact constructor.”