← Back to JavaScript, page 9

javascript-0176 · Hard senior

What is a realm in JavaScript, and why do instanceof checks fail for objects that come from an iframe or a vm context?

A realm is a full set of built-in objects, such as its own Array, Object, and Error constructors with their own prototypes, plus a global object. An iframe, a vm context, or a worker has a different realm, so an array made there is a real array but is not an instance of your Array. Use realm-independent checks such as Array.isArray, Object.prototype.toString, or private brand checks.

Full answer

Each global environment has its own copy of the standard library. A page and an iframe each have an Array, Object, Error, Promise, and Map, and their prototypes are different objects. Node.js vm contexts behave the same way. Objects can cross the border freely, because they are just references, but their prototype chains still point to the original realm.

Consequences:

  • otherArray instanceof Array is false, because Array.prototype of your realm is not in the chain of an array from another realm. The same happens for Error, Date, RegExp, Map, and Promise.
  • Array.isArray(x) works across realms, because it checks the internal type of the object, not its prototype. The same idea applies to Object.prototype.toString.call(x) (it reads Symbol.toStringTag or the internal class) and to Number.isFinite.
  • For typed or special objects in Node.js, util.types.isDate, isRegExp, isPromise, and isNativeError are safe. In browsers, Error.isError is still new, so check Object.prototype.toString or the name property when you accept errors from other frames.
  • Primitive values are not realm specific. Symbol.for('key') returns the same symbol in all realms, and well-known symbols such as Symbol.iterator are shared too, while a symbol made with Symbol('key') is unique.
  • A function from another realm has another Function.prototype, so fn instanceof Function can be false even though typeof fn === 'function' is true. typeof is realm safe.
  • Errors thrown by built-ins use the realm of the function that was called, not the caller. A TypeError from a method of an iframe's array is the iframe's TypeError.
  • Private class fields are per class definition, so #field in obj works across realms only when the same class is used, and it fails for another copy of the class loaded in another realm.
  • Two copies of a library, for example loaded in two frames, produce classes that fail each other's instanceof checks.

Practical guidance: libraries that accept user input should avoid instanceof for built-ins and use Array.isArray, typeof, duck typing, or tag checks. Symbol.hasInstance can customize instanceof. structuredClone and postMessage copy values into the receiver's realm, which removes the mismatch.

Realms are also the base of sandboxing proposals (ShadowRealm) and of test runners that run code in separate contexts. Test frameworks sometimes fail for this reason: expect(result).toBeInstanceOf(Array) can fail when result came from a vm context.

javascript
const vm = require('node:vm');
const util = require('node:util');

const foreign = vm.runInNewContext('({ list: [1, 2, 3], when: new Date(0), fail: new TypeError("other"), fn: function () {}, sym: Symbol.for("shared"), local: Symbol("local") })');

console.log('Array.isArray:', Array.isArray(foreign.list));
console.log('instanceof Array:', foreign.list instanceof Array);
console.log('toString tag:', Object.prototype.toString.call(foreign.list));
console.log('same prototype:', Object.getPrototypeOf(foreign.list) === Array.prototype);
console.log('constructor name still matches:', foreign.list.constructor.name === 'Array', foreign.list.constructor === Array);

console.log('Date instanceof:', foreign.when instanceof Date, 'util.types.isDate:', util.types.isDate(foreign.when));
console.log('Error instanceof:', foreign.fail instanceof Error, 'util.types.isNativeError:', util.types.isNativeError(foreign.fail));
console.log('function: typeof =', typeof foreign.fn, ', instanceof Function =', foreign.fn instanceof Function);
console.log('Symbol.for shared:', foreign.sym === Symbol.for('shared'), '| plain symbol shared:', foreign.local === Symbol('local'));

const cloned = structuredClone(foreign.list);
console.log('structuredClone into this realm:', cloned instanceof Array);

console.log('spread into a local array:', [...foreign.list] instanceof Array, Array.from(foreign.list) instanceof Array);

class Even {
  static [Symbol.hasInstance](value) {
    return Array.isArray(value) && value.length % 2 === 0;
  }
}
console.log('custom hasInstance, foreign array of 3:', foreign.list instanceof Even, ', of 2:', [1, 2] instanceof Even);

const text = vm.runInNewContext('typeof String(1) + typeof Object(1)');
console.log('primitives are realm neutral:', text);

Run with Node.js v24.22.1 as js-176.js; two runs gave identical output. Output: Array.isArray: true instanceof Array: false toString tag: [object Array] same prototype: false constructor name still matches: true false Date instanceof: false util.types.isDate: true Error instanceof: false util.types.isNativeError: true function: typeof = function , instanceof Function = false Symbol.for shared: true | plain symbol shared: false structuredClone into this realm: true spread into a local array: true true custom hasInstance, foreign array of 3: false , of 2: true primitives are realm neutral: stringobject

Key points

  • A realm is a global object plus its own built-in constructors and prototypes.
  • instanceof fails across realms; Array.isArray, typeof, and toString tags work.
  • Symbol.for is shared across realms, while a constructor-created class is not.
  • Errors and objects from built-ins belong to the realm of the called function.
  • Prefer realm-safe checks in libraries and use structuredClone or postMessage to copy into your realm.

Common mistakes

  • Using instanceof Array, Error, or Date on data that may come from another frame or context.
  • Assuming typeof and instanceof Function agree.
  • Loading two copies of one library and comparing their classes.
  • Using instanceof in test assertions across vm contexts.

Follow-ups

  • What does structuredClone do to the prototype of an object?
  • How does Symbol.hasInstance change the behavior of instanceof?
  • Where do you see realms in test runners or sandboxes?

Tips

  • Start with the iframe example, then name the realm-safe checks.
  • Mention Array.isArray and Symbol.for as the cross-realm safe tools.
  • Know that errors belong to the realm of the called function.