This rule raises an issue when instanceof is used to check the type of built-in JavaScript objects like String,
Number, Array, Object, etc.
Using instanceof to check built-in object types has significant limitations that can cause your code to behave unexpectedly.
The main problem is that instanceof checks whether an object was created by a specific constructor function. This works fine for
custom classes, but built-in objects can exist in different "realms" (execution contexts). For example, an array created in an iframe has a different
Array constructor than an array created in the main window, even though they’re both arrays.
When you use instanceof Array on an array from a different realm, it returns false even though the object is clearly an
array. This can break your type checking logic and cause bugs that are hard to debug.
Additionally, instanceof doesn’t work correctly with primitive values. For example, "hello" instanceof String returns
false because string literals are primitives, not String objects.
These issues make instanceof unreliable for type checking built-in types, especially in complex applications that use iframes, web
workers, or other execution contexts.
Using instanceof with built-in objects can lead to incorrect type detection, causing your application to behave unexpectedly. This is
particularly problematic in applications that work with multiple execution contexts (iframes, web workers) where the same type of object might fail
instanceof checks. The result can be runtime errors, incorrect data processing, or security vulnerabilities if type validation fails.
For primitive types (string, number, boolean, bigint, symbol), use the typeof operator instead of instanceof. This is
more reliable and works correctly with both primitive values and their object wrappers.
if (value instanceof String) { // Noncompliant
console.log('It is a string');
}
if (value instanceof Number) { // Noncompliant
return value.toFixed(2);
}
if (typeof value === 'string') {
console.log('It is a string');
}
if (typeof value === 'number') {
return value.toFixed(2);
}