useIsArray
Summary
Section titled Summary- Rule available since:
v1.0.0 - Diagnostic Category:
lint/suspicious/useIsArray - This rule is recommended, which means is enabled by default.
- This rule has an unsafe fix.
- The default severity of this rule is error.
- Sources:
- Same as
unicorn/no-instanceof-array
- Same as
Description
Section titled DescriptionUse Array.isArray() instead of instanceof Array.
In JavaScript some array-like objects such as arguments are not instances of the Array class. ///
Moreover, the global Array class can be different between two execution contexts.
For instance, two frames in a web browser have a distinct Array class.
Passing arrays across these contexts, results in arrays that are not instances of the contextual global Array class.
To avoid these issues, use Array.isArray() instead of instanceof Array.
See the MDN docs for more details.
Examples
Section titled ExamplesInvalid
Section titled Invalidconst xs = [];if (xs instanceof Array) {}code-block.js:2:5 lint/suspicious/useIsArray FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ Use Array.isArray() instead of instanceof Array.
1 │ const xs = [];
> 2 │ if (xs instanceof Array) {}
│ ^^^^^^^^^^^^^^^^^^^
3 │
ℹ instanceof Array returns false for array-like objects and arrays from other execution contexts.
ℹ Unsafe fix: Use Array.isArray() instead.
1 1 │ const xs = [];
2 │ - if·(xs·instanceof·Array)·{}
2 │ + if·(Array.isArray(xs))·{}
3 3 │
Valid
Section titled Validconst xs = [];if (Array.isArray(xs)) {}How to configure
Section titled How to configure{ "linter": { "rules": { "suspicious": { "useIsArray": "error" } } }}