Newer Version Available

This content describes an older version of this product. View Latest

Disallow instanceof (no-instanceof)

This rule aims to eliminate the use of instanceof, and direct comparison with Array or Object primitives.

The framework sometimes, for security reasons, evaluates a component’s code in a different iframe or worker. As a result your code might fail under certain conditions. For these reasons, it’s a best practice to avoid using instanceof.

Why is this? Different scopes have different execution environments. This means that they have different built-ins—different global objects, different constructors, etc. This can produce results you might, at first, find unintuitive. For example, [] instanceof window.parent.Array returns false, because Array.prototype !== window.parent.Array, and arrays inherit from the former.

You’ll encounter this issue when you’re dealing with multiple frames or windows in your script and pass objects from one context to another via functions. Because the security infrastructure of the framework does this automatically, you want to write code that behaves consistently no matter what context it executes in.

Rule Details

The following patterns are considered problematic:
1if (foo instanceof bar) {
2    // do something!
3}
4if (foo.prototype === Array) {
5    // do something
6}
7if (foo.prototype === Object) {
8    // do something else
9}
The following patterns make use of built in JavaScript or Lightning components utility functions, and are a suggested alternative:
1if (Array.isArray(foo)) {
2    // do something
3}
4if ($A.util.isPlainObject(foo)) {
5    // do something else
6}

Further Reading