File: readme.md
eslint-plugin-unicorn [](https://codecov.io/gh/sindresorhus/eslint-plugin-unicorn/branch/main) [](https://npmjs.com/package/eslint-plugin-unicorn)
More than 300 powerful ESLint rules
Most rules target JavaScript and TypeScript, but some also lint CSS, HTML, JSON, Markdown, and YAML when used with the matching ESLint language plugin.
We do not accept pull requests because of too much AI slop.
Install
npm install --save-dev eslint eslint-plugin-unicornRequires ESLint >=10.4, flat config, and ESM.
You might want to check out XO, which includes this plugin.
Usage
Use a preset config or configure each rule in eslint.config.js.
If you don't use a preset, set the same languageOptions as shown below.
import unicorn from 'eslint-plugin-unicorn';
import {defineConfig} from 'eslint/config';
import globals from 'globals';
export default defineConfig([
{
files: ['**/*.js'],
languageOptions: {
globals: globals.builtin,
},
plugins: {
unicorn,
},
rules: {
'unicorn/prefer-module': 'error',
'unicorn/โฆ': 'error',
},
},
// โฆ
]);For TypeScript, scope Unicorn to TypeScript files and configure a TypeScript parser for the same config object:
import typescriptEslintParser from '@typescript-eslint/parser';
import unicorn from 'eslint-plugin-unicorn';
import {defineConfig} from 'eslint/config';
import globals from 'globals';
export default defineConfig([
{
files: ['**/*.ts'],
languageOptions: {
globals: globals.builtin,
parser: typescriptEslintParser,
},
plugins: {
unicorn,
},
rules: {
'unicorn/prefer-module': 'error',
'unicorn/โฆ': 'error',
},
},
// โฆ
]);Rules
๐ผ Configurations enabled in.
โ
Set in the recommended configuration.
โ๏ธ Set in the unopinionated configuration.
๐ง Automatically fixable by the --fix CLI option.
๐ก Manually fixable by editor suggestions.
๐ญ Requires type information.
| Name | Description | ๐ผ | ๐ง | ๐ก | ๐ญ |
|---|---|---|---|---|---|
| better-dom-traversing | Prefer better DOM traversal APIs. | โ โ๏ธ | ๐ก | ||
| catch-error-name | Enforce a specific parameter name in catch clauses. | โ | ๐ง | ||
| class-reference-in-static-methods | Enforce consistent class references in static methods. | โ | ๐ก | ||
| comment-content | Enforce better comment content. | ๐ง | |||
| consistent-arrow-return-style | Enforce a consistent return style for multiline arrow function bodies. | ๐ง | |||
| consistent-assert | Enforce consistent assertion style with node:assert. |
โ | ๐ง | ||
| consistent-boolean-name | Enforce consistent naming for boolean names. | โ | ๐ง | ๐ก | |
| consistent-class-member-order | Enforce consistent class member order. | โ | ๐ก | ||
| consistent-compound-words | Enforce consistent spelling of compound words in identifiers. | โ โ๏ธ | ๐ก | ||
| consistent-conditional-object-spread | Enforce consistent conditional object spread style. | โ | ๐ง | ||
| consistent-date-clone | Prefer passing Date directly to the constructor when cloning. |
โ โ๏ธ | ๐ง | ||
| consistent-destructuring | Use destructured variables over properties. | ๐ก | |||
| consistent-empty-array-spread | Prefer consistent types when spreading a ternary in an array literal. | โ | ๐ง | ||
| consistent-existence-index-check | Enforce consistent style for element existence checks with indexOf(), lastIndexOf(), findIndex(), and findLastIndex(). |
โ โ๏ธ | ๐ง | ||
| consistent-export-decorator-position | Enforce consistent decorator position on exported classes. | โ โ๏ธ | ๐ง | ||
| consistent-function-scoping | Move function definitions to the highest possible scope. | โ | |||
| consistent-function-style | Enforce function syntax by role. | ๐ก | |||
| consistent-json-file-read | Enforce consistent JSON file reads before JSON.parse(). |
โ | ๐ง | ||
| consistent-optional-chaining | Enforce consistent optional chaining for same-base member access. | โ โ๏ธ | ๐ก | ||
| consistent-template-literal-escape | Enforce consistent style for escaping ${ in template literals. |
โ | ๐ง | ||
| consistent-tuple-labels | Enforce consistent labels on tuple type elements. | โ | |||
| custom-error-definition | Enforce correct Error subclassing. |
๐ง | |||
| default-export-style | Enforce consistent default export declarations. | โ | ๐ง | ๐ก | |
| dom-node-dataset | Enforce consistent style for DOM element dataset access. | โ โ๏ธ | ๐ง | ||
| empty-brace-spaces | Enforce no spaces between braces. | โ | ๐ง | ||
| error-message | Enforce passing a message value when creating a built-in error. |
โ โ๏ธ | |||
| escape-case | Require escape sequences to use uppercase or lowercase values. | โ โ๏ธ | ๐ง | ||
| expiring-todo-comments | Add expiration conditions to TODO comments. | โ โ๏ธ | |||
| explicit-length-check | Enforce explicitly comparing the length or size property of a value. |
โ | ๐ง | ๐ก | |
| explicit-timer-delay | Enforce or disallow explicit delay argument for setTimeout() and setInterval(). |
โ โ๏ธ | ๐ง | ||
| filename-case | Enforce a case style for filenames and directory names. | โ | |||
| id-match | Require identifiers to match a specified regular expression. | ||||
| import-style | Enforce specific import styles per module. | โ โ๏ธ | |||
| isolated-functions | Prevent usage of variables from outside the scope of isolated functions. | โ | |||
| iteration-fallback-style | Enforce a consistent style for optional loop sources. | ๐ง | |||
| logical-assignment-operators | Require or disallow logical assignment operator shorthand | โ | ๐ง | ๐ก | |
| max-nested-calls | Limit the depth of nested calls. | โ | |||
| name-replacements | Enforce replacements for variable, property, and filenames. | โ | ๐ง | ๐ก | |
| new-for-builtins | Enforce correct use of new for builtin constructors. |
โ โ๏ธ | ๐ง | ๐ก | |
| no-abusive-eslint-disable | Enforce specifying rules to disable in eslint-disable comments. |
โ โ๏ธ | |||
| no-accessor-recursion | Disallow recursive access to this within getters and setters. |
โ โ๏ธ | |||
| no-accidental-bitwise-operator | Disallow bitwise operators where a logical operator was likely intended. | โ โ๏ธ | ๐ก | ||
| no-anonymous-default-export | Disallow anonymous functions and classes as the default export. | โ โ๏ธ | ๐ก | ||
| no-array-callback-reference | Prevent passing a function reference directly to iterator methods. | โ | ๐ก | ||
| no-array-concat-in-loop | Disallow array accumulation with Array#concat() in loops. |
โ | |||
| no-array-fill-with-reference-type | Disallow using reference values as Array#fill() values. |
โ โ๏ธ | |||
| no-array-from-fill | Disallow .fill() after Array.from({length: โฆ}). |
โ โ๏ธ | |||
| no-array-front-mutation | Disallow front-of-array mutation. | ||||
| no-array-method-this-argument | Disallow using the this argument in array methods. |
โ โ๏ธ | ๐ง | ๐ก | |
| no-array-reduce | Disallow Array#reduce() and Array#reduceRight(). |
โ | ๐ง | ๐ก | |
| no-array-reverse | Prefer Array#toReversed() over Array#reverse(). |
โ โ๏ธ | ๐ก | ||
| no-array-sort | Prefer Array#toSorted() over Array#sort(). |
โ โ๏ธ | ๐ก | ||
| no-array-sort-for-min-max | Disallow sorting arrays to get the minimum or maximum value. | โ โ๏ธ | ๐ก | ||
| no-array-splice | Prefer Array#toSpliced() over Array#splice(). |
โ | ๐ก | ||
| no-asterisk-prefix-in-documentation-comments | Disallow asterisk prefixes in documentation comments. | ๐ง | |||
| no-async-promise-finally | Disallow async functions as Promise#finally() callbacks. |
โ โ๏ธ | |||
| no-await-expression-member | Disallow member access from await expression. | โ | ๐ง | ||
| no-await-in-promise-methods | Disallow using await in Promise method parameters. |
โ โ๏ธ | ๐ก | ||
| no-barrel-files | Disallow barrel files. | ||||
| no-blob-to-file | Disallow unnecessary Blob to File conversion. |
โ โ๏ธ | ๐ก | ||
| no-boolean-sort-comparator | Disallow boolean-returning sort comparators. | โ โ๏ธ | ๐ก | ||
| no-break-in-nested-loop | Disallow break and continue in nested loops and switches inside loops. |
โ | |||
| no-canvas-to-image | Prefer drawing canvases directly instead of converting them to images. | โ โ๏ธ | |||
| no-chained-comparison | Disallow chained comparisons such as a < b < c. |
โ โ๏ธ | ๐ก | ||
| no-collection-bracket-access | Disallow accessing Map, Set, WeakMap, and WeakSet entries with bracket notation. |
โ โ๏ธ | ๐ก | ||
| no-computed-property-existence-check | Disallow dynamic object property existence checks. | โ | ๐ก | ||
| no-confusing-array-splice | Disallow confusing uses of Array#{splice,toSpliced}(). |
โ | ๐ก | ||
| no-confusing-array-with | Disallow confusing uses of Array#with(). |
โ | |||
| no-console-spaces | Do not use leading/trailing space between console.log parameters. |
โ โ๏ธ | ๐ง | ||
| no-constant-zero-expression | Disallow arithmetic and bitwise operations that always evaluate to 0. |
โ โ๏ธ | ๐ก | ||
| no-declarations-before-early-exit | Disallow declarations before conditional early exits when they are only used after the exit. | โ โ๏ธ | ๐ง | ||
| no-document-cookie | Do not use document.cookie directly. |
โ โ๏ธ | |||
| no-double-comparison | Disallow two comparisons of the same operands that can be combined into one. | โ โ๏ธ | ๐ก | ||
| no-duplicate-if-branches | Disallow duplicate adjacent branches in if chains. | โ | |||
| no-duplicate-logical-operands | Disallow adjacent duplicate operands in logical expressions. | โ โ๏ธ | ๐ง | ๐ก | |
| no-duplicate-loops | Disallow .map() and .filter() in forโฆof and for awaitโฆof loop headers. |
โ | |||
| no-duplicate-set-values | Disallow duplicate values in Set constructor array literals. |
โ | |||
| no-empty-file | Disallow empty files. | โ โ๏ธ | |||
| no-error-property-assignment | Disallow assigning to built-in error properties. | โ โ๏ธ | |||
| no-exports-in-scripts | Disallow exports in scripts. | โ โ๏ธ | |||
| no-for-each | Prefer forโฆof over the forEach method. |
โ โ๏ธ | ๐ง | ๐ก | |
| no-for-loop | Do not use a for loop that can be replaced with a for-of loop. |
โ | ๐ง | ||
| no-global-object-property-assignment | Disallow assigning properties on the global object. | โ โ๏ธ | |||
| no-immediate-mutation | Disallow immediate mutation after variable assignment. | โ | ๐ง | ๐ก | |
| no-impossible-length-comparison | Disallow impossible comparisons against .length or .size. |
โ โ๏ธ | |||
| no-incorrect-query-selector | Disallow incorrect querySelector() and querySelectorAll() usage. |
โ | ๐ง | ||
| no-incorrect-template-string-interpolation | Disallow incorrect template literal interpolation syntax. | โ | ๐ก | ||
| no-instanceof-builtins | Disallow instanceof with built-in objects |
โ โ๏ธ | ๐ง | ๐ก | |
| no-invalid-argument-count | Disallow calling functions and constructors with an invalid number of arguments. | โ โ๏ธ | |||
| no-invalid-character-comparison | Disallow comparing a single character from a string to a multi-character string. | โ โ๏ธ | |||
| no-invalid-fetch-options | Disallow invalid options in fetch() and new Request(). |
โ โ๏ธ | |||
| no-invalid-file-input-accept | Disallow invalid accept values on file inputs. |
๐ง | |||
| no-invalid-remove-event-listener | Prevent calling EventTarget#removeEventListener() with the result of an expression. |
โ โ๏ธ | |||
| no-invalid-well-known-symbol-methods | Disallow invalid implementations of well-known symbol methods. | โ โ๏ธ | ๐ง | ๐ก | |
| no-keyword-prefix | Disallow identifiers starting with new or class. |
||||
| no-late-current-target-access | Disallow accessing event.currentTarget after the synchronous event dispatch has finished. |
โ | |||
| no-late-event-control | Disallow event-control method calls after the synchronous event dispatch has finished. | โ | |||
| no-lonely-if | Disallow if statements as the only statement in if blocks without else. |
โ โ๏ธ | ๐ง | ||
| no-loop-iterable-mutation | Disallow mutating a loop iterable during iteration. | โ | |||
| no-magic-array-flat-depth | Disallow a magic number as the depth argument in Array#flat(โฆ). |
โ โ๏ธ | |||
| no-manually-wrapped-comments | Disallow manually wrapped comments. | ๐ง | |||
| no-mismatched-map-key | Disallow checking a Map key before accessing a different key. | โ | |||
| no-misrefactored-assignment | Disallow misrefactored compound assignments where the target is duplicated in the right-hand side. | โ โ๏ธ | ๐ก | ||
| no-missing-local-resource | Disallow references to missing local resources. | ๐ง | |||
| no-multiple-promise-resolver-calls | Disallow calling Promise executor resolver functions more than once on the same execution path. | โ โ๏ธ | |||
| no-named-default | Disallow named usage of default import and export. | โ โ๏ธ | ๐ง | ||
| no-negated-array-predicate | Disallow negated array predicate calls. | โ โ๏ธ | ๐ง | ||
| no-negated-comparison | Disallow negated comparisons. | โ โ๏ธ | ๐ง | ||
| no-negated-condition | Disallow negated conditions. | โ โ๏ธ | ๐ง | ||
| no-negation-in-equality-check | Disallow negated expression in equality check. | โ โ๏ธ | ๐ก | ||
| no-nested-ternary | Disallow nested ternary expressions. | โ | ๐ง | ||
| no-new-array | Disallow new Array(). |
โ โ๏ธ | ๐ง | ๐ก | |
| no-new-buffer | Enforce the use of Buffer.from() and Buffer.alloc() instead of the deprecated new Buffer(). |
โ โ๏ธ | ๐ง | ๐ก | |
| no-non-function-verb-prefix | Disallow non-function values with function-style verb prefixes. | โ | ๐ญ | ||
| no-nonstandard-builtin-properties | Disallow non-standard properties on built-in objects. | โ โ๏ธ | |||
| no-null | Disallow the use of the null literal. |
โ | ๐ง | ๐ก | |
| no-object-as-default-parameter | Disallow the use of objects as default parameters. | โ โ๏ธ | |||
| no-object-methods-with-collections | Disallow Object methods with Map or Set. |
โ | ๐ก | ||
| no-optional-chaining-on-undeclared-variable | Disallow optional chaining on undeclared variables. | โ | |||
| no-process-exit | Disallow process.exit(). |
โ โ๏ธ | |||
| no-redundant-comparison | Disallow comparisons made redundant by an equality check in the same logical AND. | โ โ๏ธ | ๐ง | ๐ก | |
| no-return-array-push | Disallow using the return value of Array#push() and Array#unshift(). |
โ | ๐ก | ||
| no-selector-as-dom-name | Disallow selector syntax in DOM names. | โ | ๐ง | ||
| no-shorthand-property-overrides | Disallow shorthand properties that override related longhand properties. | โ โ๏ธ | |||
| no-single-promise-in-promise-methods | Disallow passing single-element arrays to Promise methods. |
โ โ๏ธ | ๐ง | ๐ก | |
| no-static-only-class | Disallow classes that only have static members. | โ โ๏ธ | ๐ง | ||
| no-subtraction-comparison | Prefer comparing values directly over subtracting and comparing to 0. |
โ โ๏ธ | ๐ง | ๐ก | |
| no-thenable | Disallow then property. |
โ โ๏ธ | |||
| no-this-assignment | Disallow assigning this to a variable. |
โ โ๏ธ | |||
| no-this-outside-of-class | Disallow this outside of classes. |
โ | |||
| no-top-level-assignment-in-function | Disallow assigning to top-level variables from inside functions. | โ | |||
| no-top-level-side-effects | Disallow top-level side effects in exported modules. | โ โ๏ธ | |||
| no-transition-all | Disallow all as a transition property. |
โ โ๏ธ | |||
| no-typeof-undefined | Disallow comparing undefined using typeof. |
โ โ๏ธ | ๐ง | ๐ก | |
| no-uncalled-method | Disallow referencing methods without calling them. | โ | |||
| no-undeclared-class-members | Require class members to be declared. | โ | ๐ก | ||
| no-unnecessary-array-flat-depth | Disallow using 1 as the depth argument of Array#flat(). |
โ โ๏ธ | ๐ง | ||
| no-unnecessary-array-flat-map | Disallow Array#flatMap() callbacks that only wrap a single item. |
โ | ๐ง | ๐ก | |
| no-unnecessary-array-splice-count | Disallow using .length or Infinity as the deleteCount or skipCount argument of Array#{splice,toSpliced}(). |
โ โ๏ธ | ๐ง | ||
| no-unnecessary-await | Disallow awaiting non-promise values. | โ โ๏ธ | ๐ง | ||
| no-unnecessary-boolean-comparison | Disallow unnecessary comparisons against boolean literals. | โ | ๐ง | ||
| no-unnecessary-fetch-options | Disallow unnecessary options in fetch() and new Request(). |
โ โ๏ธ | ๐ง | ||
| no-unnecessary-global-this | Disallow unnecessary globalThis references. |
โ โ๏ธ | ๐ง | ||
| no-unnecessary-nested-ternary | Disallow unnecessary nested ternary expressions. | โ โ๏ธ | ๐ง | ||
| no-unnecessary-polyfills | Enforce the use of built-in methods instead of unnecessary polyfills. | โ โ๏ธ | |||
| no-unnecessary-slice-end | Disallow using .length or Infinity as the end argument of {Array,String,TypedArray}#slice(). |
โ โ๏ธ | ๐ง | ||
| no-unnecessary-splice | Disallow Array#splice() when simpler alternatives exist. |
โ | ๐ง | ||
| no-unnecessary-string-trim | Disallow String#trim() before String#startsWith() or String#endsWith(). |
โ โ๏ธ | ๐ง | ||
| no-unreadable-array-destructuring | Disallow unreadable array destructuring. | โ โ๏ธ | ๐ง | ||
| no-unreadable-for-of-expression | Disallow unreadable iterable expressions in forโฆof and for awaitโฆof loop headers. |
โ | |||
| no-unreadable-iife | Disallow unreadable IIFEs. | โ โ๏ธ | ๐ก | ||
| no-unreadable-new-expression | Disallow unreadable new expressions. |
||||
| no-unreadable-object-destructuring | Disallow unreadable object destructuring. | โ โ๏ธ | |||
| no-unsafe-buffer-conversion | Prevent unsafe use of ArrayBuffer view .buffer. |
โ โ๏ธ | ๐ก | ||
| no-unsafe-dom-html | Disallow unsafe DOM HTML APIs. | ||||
| no-unsafe-promise-all-settled-values | Disallow reading .value from Promise.allSettled() results without a fulfilled status guard. |
โ โ๏ธ | |||
| no-unsafe-property-key | Disallow unsafe values as property keys. | โ | |||
| no-unsafe-sqlite-interpolation | Disallow interpolation into SQL strings passed to Nodeโs node:sqlite APIs. |
โ โ๏ธ | |||
| no-unsafe-string-replacement | Disallow non-literal replacement values in String#replace() and String#replaceAll(). |
โ | |||
| no-unused-array-method-return | Disallow ignoring the return value of selected array methods. | โ โ๏ธ | |||
| no-unused-properties | Disallow unused object properties. | ||||
| no-useless-boolean-cast | Disallow unnecessary Boolean() casts in array predicate callbacks. |
โ โ๏ธ | ๐ง | ||
| no-useless-coercion | Disallow useless type coercions of values that are already of the target type. | โ โ๏ธ | ๐ง | ||
| no-useless-collection-argument | Disallow useless values or fallbacks in Set, Map, WeakSet, or WeakMap. |
โ โ๏ธ | ๐ง | ๐ก | |
| no-useless-compound-assignment | Disallow useless compound assignments such as x += 0. |
โ โ๏ธ | ๐ก | ||
| no-useless-concat | Disallow useless concatenation of literals. | โ โ๏ธ | ๐ง | ||
| no-useless-continue | Disallow useless continue statements. |
โ โ๏ธ | ๐ง | ||
| no-useless-delete-check | Disallow unnecessary existence checks before deletion. | โ โ๏ธ | ๐ง | ๐ก | |
| no-useless-else | Disallow else after a statement that exits. |
โ | ๐ง | ||
| no-useless-error-capture-stack-trace | Disallow unnecessary Error.captureStackTrace(โฆ). |
โ โ๏ธ | ๐ง | ||
| no-useless-fallback-in-spread | Disallow useless fallback when spreading in object literals. | โ โ๏ธ | ๐ง | ||
| no-useless-iterator-to-array | Disallow unnecessary .toArray() on iterators. |
โ โ๏ธ | ๐ง | ๐ก | |
| no-useless-length-check | Disallow useless array length check. | โ โ๏ธ | ๐ง | ||
| no-useless-logical-operand | Disallow unnecessary operands in logical expressions involving boolean literals. | โ โ๏ธ | ๐ง | ||
| no-useless-override | Disallow useless overrides of class methods. | โ โ๏ธ | ๐ง | ||
| no-useless-promise-resolve-reject | Disallow returning/yielding Promise.resolve/reject() in async functions or promise callbacks |
โ โ๏ธ | ๐ง | ||
| no-useless-re-export | Disallow redundant re-exports. | โ โ๏ธ | |||
| no-useless-recursion | Disallow simple recursive function calls that can be replaced with a loop. | โ | |||
| no-useless-spread | Disallow unnecessary spread. | โ โ๏ธ | ๐ง | ๐ก | |
| no-useless-switch-case | Disallow useless case in switch statements. | โ โ๏ธ | ๐ก | ||
| no-useless-template-literals | Disallow useless template literal expressions. | โ โ๏ธ | ๐ง | ๐ก | |
| no-useless-undefined | Disallow useless undefined. |
โ โ๏ธ | ๐ง | ๐ก | |
| no-xor-as-exponentiation | Disallow the bitwise XOR operator where exponentiation was likely intended. | โ โ๏ธ | ๐ก | ||
| no-zero-fractions | Disallow number literals with zero fractions or dangling dots. | โ โ๏ธ | ๐ง | ||
| number-literal-case | Enforce proper case for numeric literals. | โ โ๏ธ | ๐ง | ||
| numeric-separators-style | Enforce the style of numeric separators by correctly grouping digits. | โ โ๏ธ | ๐ง | ||
| operator-assignment | Require assignment operator shorthand where possible. | โ | ๐ง | ๐ก | |
| prefer-abort-signal-any | Prefer AbortSignal.any() over manually forwarding abort events between signals. |
โ | ๐ก | ||
| prefer-abort-signal-timeout | Prefer AbortSignal.timeout() over manually aborting an AbortController with setTimeout(). |
โ | ๐ก | ||
| prefer-add-event-listener | Prefer .addEventListener() and .removeEventListener() over on-functions. |
โ โ๏ธ | ๐ง | ||
| prefer-add-event-listener-options | Prefer an options object over a boolean in .addEventListener(). |
โ โ๏ธ | ๐ง | ||
| prefer-aggregate-error | Prefer AggregateError when throwing collected errors. |
โ โ๏ธ | ๐ง | ||
| prefer-array-find | Prefer .find(โฆ) and .findLast(โฆ) over the first or last element from .filter(โฆ). |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-array-flat | Prefer Array#flat() over legacy techniques to flatten arrays. |
โ โ๏ธ | ๐ง | ||
| prefer-array-flat-map | Prefer .flatMap(โฆ) over .map(โฆ).flat() and .filter(โฆ).flatMap(โฆ). |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-array-from-async | Prefer Array.fromAsync() over for awaitโฆof array accumulation. |
โ | ๐ง | ||
| prefer-array-from-map | Prefer using the Array.from() mapping function argument. |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-array-from-range | Prefer Array.from({length}, โฆ) when creating range arrays. |
โ โ๏ธ | ๐ง | ||
| prefer-array-index-of | Prefer Array#{indexOf,lastIndexOf}() over Array#{findIndex,findLastIndex}() when looking for the index of an item. |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-array-iterable-methods | Prefer iterating an array directly or with Array#keys() over Array#entries() when the index or value is unused. |
โ | ๐ง | ||
| prefer-array-last-methods | Prefer last-oriented array methods over Array#reverse() or Array#toReversed() followed by a method. |
โ โ๏ธ | ๐ก | ||
| prefer-array-slice | Prefer Array#slice() over Array#splice() when reading from the returned array. |
โ | ๐ก | ||
| prefer-array-some | Prefer .some(โฆ) over .filter(โฆ).length check and .{find,findLast,findIndex,findLastIndex}(โฆ). |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-at | Prefer .at() method for index access and String#charAt(). |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-await | Prefer await over promise chaining. |
โ โ๏ธ | ๐ก | ||
| prefer-bigint-literals | Prefer BigInt literals over the constructor. |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-blob-reading-methods | Prefer Blob#arrayBuffer() over FileReader#readAsArrayBuffer(โฆ) and Blob#text() over FileReader#readAsText(โฆ). |
โ โ๏ธ | |||
| prefer-block-statement-over-iife | Prefer block statements over IIFEs used only for scoping. | โ โ๏ธ | ๐ง | ||
| prefer-boolean-return | Prefer directly returning boolean expressions over if statements. |
โ โ๏ธ | ๐ง | ||
| prefer-class-fields | Prefer class field declarations over this assignments in constructors. |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-classlist-toggle | Prefer using Element#classList.toggle() to toggle class names. |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-code-point | Prefer String#codePointAt(โฆ) over String#charCodeAt(โฆ) and String.fromCodePoint(โฆ) over String.fromCharCode(โฆ). |
โ โ๏ธ | ๐ก | ||
| prefer-continue | Prefer early continues over whole-loop conditional wrapping. | โ | ๐ง | ||
| prefer-date-now | Prefer Date.now() to get the number of milliseconds since the Unix Epoch. |
โ โ๏ธ | ๐ง | ||
| prefer-default-parameters | Prefer default parameters over reassignment. | โ โ๏ธ | ๐ก | ||
| prefer-direct-iteration | Prefer direct iteration over default iterator method calls. | โ โ๏ธ | ๐ง | ||
| prefer-dispose | Prefer using using/await using over manual try/finally resource disposal. |
๐ก | |||
| prefer-dom-node-append | Prefer Element#append() over Node#appendChild(). |
โ โ๏ธ | ๐ง | ||
| prefer-dom-node-html-methods | Prefer .getHTML() and .setHTML() over .innerHTML. |
โ | ๐ง | ๐ก | |
| prefer-dom-node-remove | Prefer childNode.remove() over parentNode.removeChild(childNode). |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-dom-node-replace-children | Prefer .replaceChildren() when emptying DOM children. |
โ โ๏ธ | ๐ง | ||
| prefer-dom-node-text-content | Prefer .textContent over .innerText. |
โ โ๏ธ | ๐ก | ||
| prefer-early-return | Prefer early returns over full-function conditional wrapping. | โ โ๏ธ | ๐ง | ๐ก | |
| prefer-else-if | Prefer else if over adjacent if statements with related conditions. |
โ | ๐ง | ๐ก | |
| prefer-error-is-error | Prefer Error.isError() when checking for errors. |
๐ง | |||
| prefer-event-target | Prefer EventTarget over EventEmitter. |
โ โ๏ธ | |||
| prefer-explicit-viewport-units | Prefer explicit viewport units. | ๐ก | |||
| prefer-export-from | Prefer exportโฆfrom when re-exporting. |
โ | ๐ง | ๐ก | |
| prefer-flat-math-min-max | Prefer flat Math.min() and Math.max() calls over nested calls. |
โ โ๏ธ | ๐ง | ||
| prefer-get-or-insert-computed | Prefer .getOrInsertComputed() when the default value has side effects. |
โ | ๐ง | ||
| prefer-global-number-constants | Prefer global numeric constants over Number static properties. |
โ โ๏ธ | ๐ง | ||
| prefer-global-this | Prefer globalThis over window, self, and global. |
โ โ๏ธ | ๐ง | ||
| prefer-group-by | Prefer Object.groupBy() or Map.groupBy() over reduce-based grouping. |
โ | ๐ง | ||
| prefer-has-check | Prefer .has() when checking existence. |
โ โ๏ธ | ๐ง | ||
| prefer-hoisting-branch-code | Prefer moving code shared by all branches of an if statement out of the branches. |
โ | ๐ง | ๐ก | |
| prefer-https | Prefer HTTPS over HTTP. | โ | ๐ง | ||
| prefer-identifier-import-export-specifiers | Prefer identifiers over string literals in import and export specifiers. | โ โ๏ธ | ๐ง | ||
| prefer-import-meta-properties | Prefer import.meta.{dirname,filename} over legacy techniques for getting file paths. |
๐ง | |||
| prefer-includes | Prefer .includes() over .indexOf(), .lastIndexOf(), and Array#some() when checking for existence or non-existence. |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-includes-over-repeated-comparisons | Prefer .includes() over repeated equality comparisons. |
โ | |||
| prefer-iterable-in-constructor | Prefer passing iterables directly to constructors instead of filling empty collections. | โ โ๏ธ | ๐ง | ||
| prefer-iterator-concat | Prefer Iterator.concat(โฆ) over temporary spread arrays. |
๐ง | ๐ก | ||
| prefer-iterator-helpers | Prefer iterator helpers over temporary arrays from iterators. | โ โ๏ธ | ๐ก | ||
| prefer-iterator-to-array | Prefer Iterator#toArray() over temporary arrays from iterator spreads. |
โ | ๐ง | ๐ก | |
| prefer-iterator-to-array-at-end | Prefer moving .toArray() to the end of iterator helper chains. |
โ โ๏ธ | ๐ก | ||
| prefer-keyboard-event-key | Prefer KeyboardEvent#key over deprecated keyboard event properties. |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-location-assign | Prefer location.assign() over assigning to location.href. |
โ | ๐ง | ||
| prefer-logical-operator-over-ternary | Prefer using a logical operator over a ternary. | โ โ๏ธ | ๐ก | ||
| prefer-map-from-entries | Prefer new Map() over Object.fromEntries() when using the result as a map. |
โ โ๏ธ | ๐ง | ||
| prefer-math-abs | Prefer Math.abs() over manual absolute value expressions and symmetric range checks. |
โ โ๏ธ | ๐ง | ||
| prefer-math-constants | Prefer Math constants over their approximate numeric values. |
โ โ๏ธ | ๐ก | ||
| prefer-math-min-max | Prefer Math.min() and Math.max() over ternaries for simple comparisons. |
โ โ๏ธ | ๐ง | ||
| prefer-math-trunc | Prefer Math.trunc() for truncating numbers. |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-minimal-ternary | Prefer moving ternaries into the minimal varying part of an expression. | โ โ๏ธ | |||
| prefer-modern-dom-apis | Prefer modern DOM APIs. | โ โ๏ธ | ๐ง | ||
| prefer-modern-math-apis | Prefer modern Math APIs over legacy patterns. |
โ โ๏ธ | ๐ง | ||
| prefer-module | Prefer JavaScript modules (ESM) over CommonJS. | โ โ๏ธ | ๐ง | ๐ก | |
| prefer-native-coercion-functions | Prefer using String, Number, BigInt, Boolean, and Symbol directly. |
โ โ๏ธ | ๐ง | ||
| prefer-negative-index | Prefer negative index over .length - index when possible. |
โ โ๏ธ | ๐ง | ||
| prefer-node-protocol | Prefer using the node: protocol when importing Node.js builtin modules. |
โ โ๏ธ | ๐ง | ||
| prefer-number-coercion | Prefer Number() over parseFloat() and base-10 parseInt(). |
โ โ๏ธ | ๐ก | ||
| prefer-number-is-safe-integer | Prefer Number.isSafeInteger() over integer checks. |
โ | ๐ก | ||
| prefer-number-properties | Prefer Number static methods over global functions and optionally static properties over global constants. |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-object-define-properties | Prefer Object.defineProperties() over multiple Object.defineProperty() calls. |
โ โ๏ธ | ๐ง | ||
| prefer-object-destructuring-defaults | Prefer object destructuring defaults over default object literals with spread. | โ | ๐ก | ||
| prefer-object-from-entries | Prefer using Object.fromEntries(โฆ) to transform a list of key-value pairs into an object. |
โ โ๏ธ | ๐ง | ||
| prefer-object-iterable-methods | Prefer the most specific Object iterable method. |
โ โ๏ธ | ๐ง | ||
| prefer-observer-apis | Prefer observer APIs over resize and scroll listeners with layout reads. | โ | |||
| prefer-optional-catch-binding | Prefer omitting the catch binding parameter. |
โ โ๏ธ | ๐ง | ||
| prefer-path2d | Prefer Path2D for repeatedly drawn canvas paths. |
โ โ๏ธ | |||
| prefer-private-class-fields | Prefer private class fields over the underscore-prefix convention. | โ | ๐ง | ||
| prefer-promise-try | Prefer Promise.try() over promise-wrapping boilerplate. |
โ | ๐ง | ||
| prefer-promise-with-resolvers | Prefer Promise.withResolvers() when extracting resolver functions from new Promise(). |
โ โ๏ธ | ๐ง | ||
| prefer-prototype-methods | Prefer borrowing methods from the prototype instead of the instance. | โ โ๏ธ | ๐ง | ||
| prefer-query-selector | Prefer .querySelector() and .querySelectorAll() over older DOM query methods. |
โ | ๐ง | ||
| prefer-queue-microtask | Prefer queueMicrotask() over process.nextTick(), setImmediate(), and setTimeout(โฆ, 0). |
โ โ๏ธ | ๐ง | ||
| prefer-reflect-apply | Prefer Reflect.apply() over Function#apply(). |
โ โ๏ธ | ๐ง | ||
| prefer-regexp-escape | Prefer RegExp.escape() for escaping strings to use in regular expressions. |
๐ง | ๐ก | ||
| prefer-regexp-test | Prefer RegExp#test() over String#match(), String#search(), and RegExp#exec(). |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-response-static-json | Prefer Response.json() over new Response(JSON.stringify()). |
โ โ๏ธ | ๐ง | ||
| prefer-scoped-selector | Prefer :scope when using element query selector methods. |
โ | ๐ก | ||
| prefer-set-has | Prefer Set#has() over Array#includes() when checking for existence or non-existence. |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-set-methods | Prefer Set methods for Set operations. |
โ | ๐ง | ๐ก | |
| prefer-set-size | Prefer using Set#size instead of Array#length. |
โ โ๏ธ | ๐ง | ||
| prefer-short-arrow-method | Prefer arrow function properties over methods with a single return. | ๐ง | |||
| prefer-simple-condition-first | Prefer simple conditions first in logical expressions. | โ | ๐ง | ||
| prefer-simple-sort-comparator | Prefer a simple comparison function for Array#sort(). |
โ โ๏ธ | ๐ก | ||
| prefer-simplified-conditions | Prefer simplified conditions. | โ โ๏ธ | ๐ง | ||
| prefer-single-array-predicate | Prefer a single Array#some() or Array#every() with a combined predicate. |
โ โ๏ธ | ๐ก | ||
| prefer-single-call | Enforce combining multiple Array#{push,unshift}(), Element#classList.{add,remove}(), and importScripts() into one call. |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-single-object-destructuring | Prefer a single object destructuring declaration per local const source. | โ | ๐ง | ||
| prefer-single-replace | Enforce combining multiple single-character replacements into a single String#replaceAll() with a regular expression. |
โ โ๏ธ | ๐ง | ||
| prefer-smaller-scope | Prefer declaring variables in the smallest possible scope. | โ | ๐ง | ||
| prefer-split-limit | Prefer String#split() with a limit. |
โ โ๏ธ | ๐ง | ||
| prefer-spread | Prefer the spread operator over Array.from(โฆ), Array#concat(โฆ), Array#{slice,toSpliced}(), and trivial forโฆof copies. |
โ | ๐ง | ๐ก | |
| prefer-string-match-all | Prefer String#matchAll() over RegExp#exec() loops. |
โ โ๏ธ | ๐ง | ||
| prefer-string-pad-start-end | Prefer String#padStart() and String#padEnd() over manual string padding. |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-string-raw | Prefer using the String.raw tag to avoid escaping \. |
โ โ๏ธ | ๐ง | ||
| prefer-string-repeat | Prefer String#repeat() for repeated whitespace. |
โ โ๏ธ | ๐ง | ||
| prefer-string-replace-all | Prefer String#replaceAll() over regex searches with the global flag and String#split().join(). |
โ โ๏ธ | ๐ง | ||
| prefer-string-slice | Prefer String#slice() over String#substr() and String#substring(). |
โ โ๏ธ | ๐ง | ||
| prefer-string-starts-ends-with | Prefer String#startsWith() & String#endsWith() over regexes, String#indexOf() === 0, and slice checks. |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-string-trim-start-end | Prefer String#trimStart() / String#trimEnd() over String#trimLeft() / String#trimRight(). |
โ โ๏ธ | ๐ง | ||
| prefer-structured-clone | Prefer using structuredClone to create a deep clone. |
โ โ๏ธ | ๐ก | ||
| prefer-switch | Prefer switch over multiple else-if. |
โ โ๏ธ | ๐ง | ||
| prefer-temporal | Prefer Temporal over Date. |
๐ง | ๐ก | ||
| prefer-ternary | Prefer ternary expressions over simple if statements that return or assign values. |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-then-catch | Prefer .then().catch() over .then(โฆ, โฆ) for error handling. |
โ | ๐ก | ||
| prefer-toggle-attribute | Prefer using Element#toggleAttribute() to toggle attributes. |
โ โ๏ธ | ๐ง | ๐ก | |
| prefer-top-level-await | Prefer top-level await over top-level promises and async function calls. | โ โ๏ธ | ๐ก | ||
| prefer-type-error | Enforce throwing TypeError in type checking conditions. |
โ โ๏ธ | ๐ง | ||
| prefer-type-literal-last | Require type literals to be last in union types. | โ | ๐ง | ||
| prefer-uint8array-base64 | Prefer Uint8Array#toBase64() and Uint8Array.fromBase64() over atob(), btoa(), and Buffer base64 conversions. |
๐ก | |||
| prefer-unary-minus | Prefer the unary minus operator over multiplying or dividing by -1. |
โ โ๏ธ | ๐ง | ||
| prefer-unicode-code-point-escapes | Prefer Unicode code point escapes over legacy escape sequences. | โ โ๏ธ | ๐ง | ๐ก | |
| prefer-url-can-parse | Prefer URL.canParse() over constructing a URL in a try/catch for validation. |
โ โ๏ธ | ๐ง | ||
| prefer-url-href | Prefer URL#href over stringifying a URL. |
โ โ๏ธ | ๐ง | ||
| prefer-url-search-parameters | Prefer URLSearchParams over manually splitting query strings. |
โ โ๏ธ | ๐ก | ||
| prefer-while-loop-condition | Prefer putting the condition in the while statement. | โ โ๏ธ | ๐ง | ||
| relative-url-style | Enforce consistent relative URL style. | โ โ๏ธ | ๐ง | ๐ก | |
| require-array-join-separator | Enforce using the separator argument with Array#join(). |
โ โ๏ธ | ๐ง | ||
| require-array-sort-compare | Require a compare function when calling Array#sort() or Array#toSorted(). |
โ โ๏ธ | ๐ก | ||
| require-css-escape | Require CSS.escape() for interpolated values in CSS selectors. |
โ โ๏ธ | ๐ง | ||
| require-frontmatter-fields | Require configured YAML frontmatter fields. | ||||
| require-module-attributes | Require non-empty module attributes for imports and exports | โ โ๏ธ | ๐ง | ||
| require-module-specifiers | Require non-empty specifier list in import and export statements. | โ โ๏ธ | ๐ง | ๐ก | |
| require-number-to-fixed-digits-argument | Enforce using the digits argument with Number#toFixed(). |
โ โ๏ธ | ๐ง | ||
| require-passive-events | Require passive event listeners for high-frequency events. | โ โ๏ธ | ๐ง | ||
| require-post-message-target-origin | Enforce using the targetOrigin argument with window.postMessage(). |
๐ก | |||
| require-proxy-trap-boolean-return | Require boolean-returning Proxy traps to return booleans. | โ โ๏ธ | ๐ง | ||
| single-line-block-comment-style | Enforce a consistent style for single-line block comments. | โ | ๐ง | ||
| string-content | Enforce better string content. | ๐ง | ๐ก | ||
| switch-case-braces | Enforce consistent brace style for case clauses. |
โ | ๐ง | ||
| switch-case-break-position | Enforce consistent break/return/continue/throw position in case clauses. |
โ | ๐ง | ||
| template-indent | Fix whitespace-insensitive template indentation. | โ | ๐ง | ||
| text-encoding-identifier-case | Enforce consistent case for text encoding identifiers. | โ โ๏ธ | ๐ง | ๐ก | |
| throw-new-error | Require new when creating an error. |
โ โ๏ธ | ๐ง | ||
| try-complexity | Limit the complexity of try blocks. |
Non-JavaScript files
While most rules target JavaScript and TypeScript, some also lint other file types when used with the corresponding ESLint language plugin such as @eslint/css, @eslint/json, @eslint/markdown, @html-eslint/eslint-plugin, or eslint-plugin-yml. Each such rule declares this with the meta.languages field.
When linting JSON, CSS, Markdown, HTML, or other non-JavaScript languages in the same ESLint config, scope Unicorn's JavaScript rule config objects with files. Include TypeScript/JSX extensions there only if your config already provides the matching parser/language setup for those files.
For example, keep Unicorn's JavaScript rules scoped separately, and enable only compatible Unicorn rules in each non-JavaScript language config:
import css from '@eslint/css';
import json from '@eslint/json';
import markdown from '@eslint/markdown';
import html from '@html-eslint/eslint-plugin';
import unicorn from 'eslint-plugin-unicorn';
import {defineConfig} from 'eslint/config';
export default defineConfig([
{
files: ['**/*.js'],
plugins: {
unicorn,
},
extends: [
'unicorn/recommended',
],
},
{
files: ['**/*.json'],
plugins: {
json,
unicorn,
},
language: 'json/json',
rules: {
'unicorn/no-empty-file': 'error',
'unicorn/prefer-https': 'error',
},
},
{
files: ['**/*.css'],
plugins: {
css,
unicorn,
},
language: 'css/css',
rules: {
'unicorn/prefer-explicit-viewport-units': 'error',
'unicorn/prefer-https': 'error',
'unicorn/text-encoding-identifier-case': 'error',
},
},
{
files: ['**/*.html'],
plugins: {
html,
unicorn,
},
language: 'html/html',
rules: {
'unicorn/no-invalid-file-input-accept': 'error',
'unicorn/prefer-https': 'error',
},
},
{
files: ['**/*.md'],
plugins: {
markdown,
unicorn,
},
language: 'markdown/commonmark',
rules: {
'unicorn/expiring-todo-comments': 'error',
'unicorn/prefer-https': 'error',
},
},
]);These rules work on any file type:
These rules also work on specific non-JavaScript languages:
| Name | CSS | HTML | JSON | Markdown | YAML |
|---|---|---|---|---|---|
expiring-todo-comments |
โ | โ | โ | โ | โ |
no-empty-file |
โ | โ | โ | โ | โ |
no-invalid-file-input-accept |
โ | ||||
no-manually-wrapped-comments |
โ | ||||
no-missing-local-resource |
โ | โ | โ | ||
no-shorthand-property-overrides |
โ | ||||
no-transition-all |
โ | ||||
prefer-explicit-viewport-units |
โ | ||||
require-frontmatter-fields |
โ | ||||
text-encoding-identifier-case |
โ | โ |
Deleted and deprecated rules
See the list.
Preset configs
See the ESLint docs for more information about extending config files.
Note: Preset configs will also enable the correct language options.
Recommended config
This plugin exports a recommended config that enforces good practices.
import unicorn from 'eslint-plugin-unicorn';
import {defineConfig} from 'eslint/config';
export default defineConfig([
// โฆ
{
files: ['**/*.js'],
plugins: {
unicorn,
},
extends: [
'unicorn/recommended',
],
rules: {
'unicorn/prefer-module': 'warn',
},
},
]);All config
This plugin exports an all config that enables every JavaScript-compatible rule, except deprecated ones.
import unicorn from 'eslint-plugin-unicorn';
import {defineConfig} from 'eslint/config';
export default defineConfig([
// โฆ
{
files: ['**/*.js'],
plugins: {
unicorn,
},
extends: [
'unicorn/all',
],
rules: {
'unicorn/prefer-module': 'warn',
},
},
]);Related
- eslint-node-test โ ESLint rules for the Node.js built-in test runner.
- eslint-package-json โ Powerful ESLint rules for
package.json.
File: docs/rules/catch-error-name.md
catch-error-name
๐ Enforce a specific parameter name in catch clauses.
๐ผ๐ซ This rule is enabled in the โ
recommended config. This rule is disabled in the โ๏ธ unopinionated config.
๐ง This rule is automatically fixable by the --fix CLI option.
Enforces a consistent name for caught errors across:
try/catchclauses.catch(โฆ)Promise handlers.then(โฆ, rejectionHandler)Promise handlers
Using one recognizable name makes error handlers easier to scan and avoids renaming the same concept across callback styles.
The desired parameter name is configurable, but defaults to error.
The following names are ignored:
_, but only if the error is not used.- Descriptive names, for example,
fsErrororauthError. - Names matching
options.ignore.
Examples
// โ
try {} catch (badName) {}
// โ
try {} catch (error) {}// โ
promise.catch(badName => {});
// โ
promise.catch(error => {});// โ
promise.then(undefined, badName => {});
// โ
promise.then(undefined, error => {});// โ
try {} catch (_) {
console.log(_);
}
// โ
// Underscore is allowed when the error is not used
try {} catch (_) {
// error is not used
}// โ
// Descriptive name is allowed
try {} catch (fsError) {}// โ
// `error_` is allowed because of shadowed variables
try {} catch (error_) {
const error = new Error('๐ฆ');
}Options
name
Type: string
Default: 'error'
You can set the name option like this:
'unicorn/catch-error-name': [
'error',
{
name: 'exception',
},
]ignore
Type: Array<string | RegExp>
Default: []
This option lets you specify a regex pattern for matches to ignore.
When a string is given, it's interpreted as a regular expression inside a string.
'unicorn/catch-error-name': [
'error',
{
ignore: [
'^error\\d*$',
/^ignore/i,
],
},
]With ^unicorn$, this would fail:
try {} catch (pony) {}And this would pass:
try {} catch (unicorn) {}Tip
In order to avoid shadowing in nested catch clauses, the auto-fix rule appends underscores to the identifier name.
File: docs/rules/consistent-assert.md
consistent-assert
๐ Enforce consistent assertion style with node:assert.
๐ผ๐ซ This rule is enabled in the โ
recommended config. This rule is disabled in the โ๏ธ unopinionated config.
๐ง This rule is automatically fixable by the --fix CLI option.
Prefer assert.ok() over assert() for its explicit intent and better readability. It aligns with other assert methods, ensuring consistency and making code easier to maintain and understand.
Examples
import assert from 'node:assert/strict';
assert.strictEqual(actual, expected);
assert.deepStrictEqual(actual, expected);
// โ
assert(divide(10, 2) === 5);
// โ
assert.ok(divide(10, 2) === 5);import assert from 'node:assert';
assert.strictEqual(actual, expected);
assert.deepStrictEqual(actual, expected);
// โ
assert(divide(10, 2) === 5);
// โ
assert.ok(divide(10, 2) === 5);import {strict as assert} from 'node:assert';
assert.strictEqual(actual, expected);
assert.deepStrictEqual(actual, expected);
// โ
assert(divide(10, 2) === 5);
// โ
assert.ok(divide(10, 2) === 5);File: docs/rules/consistent-date-clone.md
consistent-date-clone
๐ Prefer passing Date directly to the constructor when cloning.
๐ผ This rule is enabled in the following configs: โ
recommended, โ๏ธ unopinionated.
๐ง This rule is automatically fixable by the --fix CLI option.
The Date constructor can clone a Date object directly when passed as an argument. This is simpler and more efficient than extracting the timestamp with .getTime().
Note: This approach requires ES2015 (ES6) or later. In older environments,
new Date(date)converts to a string first, but modern JavaScript handles this correctly.
Examples
// โ
new Date(date.getTime());
// โ
new Date(date);// โ
const cloned = new Date(originalDate.getTime());
// โ
const cloned = new Date(originalDate);// โ
// When you need just the timestamp value
const timestamp = date.getTime();File: docs/rules/consistent-destructuring.md
consistent-destructuring
๐ Use destructured variables over properties.
๐ซ This rule is disabled in the following configs: โ
recommended, โ๏ธ unopinionated.
๐ก This rule is manually fixable by editor suggestions.
Enforces the use of already destructured variables over accessing the same direct, non-computed identifier property again. Previous destructurings are easily missed which leads to an inconsistent code style.
This rule is partly fixable. It does not suggest adding new properties to existing destructuring patterns, as that could read properties earlier than before.
There is no option to ignore specific sources or properties. Properties without a corresponding destructured variable are ignored by design.
Examples
// โ
const {a} = foo;
console.log(foo.a);
// โ
const {a} = foo;
console.log(a);
// โ
console.log(foo.a, foo.b);// โ
const {a} = foo;
console.log(a, foo.b);// โ
const {
a: {b},
} = foo;
console.log(foo.a.c);// โ
const {bar} = foo;
const {a} = foo.bar;
// โ
const {bar} = foo;
const {a} = bar;// โ
const {a} = foo;
console.log(a, foo.b());// โ
const {a} = foo.bar;
console.log(foo.bar.a);File: docs/rules/consistent-empty-array-spread.md
consistent-empty-array-spread
๐ Prefer consistent types when spreading a ternary in an array literal.
๐ผ๐ซ This rule is enabled in the โ
recommended config. This rule is disabled in the โ๏ธ unopinionated config.
๐ง This rule is automatically fixable by the --fix CLI option.
When spreading a ternary in an array, we can use both [] and '' as fallbacks, but it's better to have consistent types in both branches.
Examples
// โ
const array = [
a,
...(foo ? [b, c] : ''),
];
// โ
const array = [
a,
...(foo ? 'bc' : []),
];
// โ
const array = [
a,
...(foo ? [b, c] : []),
];
// โ
const array = [
a,
...(foo ? 'bc' : ''),
];File: docs/rules/consistent-existence-index-check.md
consistent-existence-index-check
๐ Enforce consistent style for element existence checks with indexOf(), lastIndexOf(), findIndex(), and findLastIndex().
๐ผ This rule is enabled in the following configs: โ
recommended, โ๏ธ unopinionated.
๐ง This rule is automatically fixable by the --fix CLI option.
Enforce consistent style for element existence checks with indexOf(), lastIndexOf(), findIndex(), and findLastIndex().
Prefer using index === -1 to check if an element does not exist and index !== -1 to check if an element does exist.
The value -1 is the sentinel returned by these methods when no match is found, so comparing it directly with === or !== makes the check read as a not-found sentinel check instead of a numeric range check.
Similar to the explicit-length-check rule.
Examples
const index = foo.indexOf('bar');
// โ
if (index < 0) {}
// โ
if (index === -1) {}const index = foo.indexOf('bar');
// โ
if (index >= 0) {}
// โ
if (index !== -1) {}const index = foo.indexOf('bar');
// โ
if (index > -1) {}
// โ
if (index !== -1) {}const index = foo.lastIndexOf('bar');
// โ
if (index >= 0) {}
// โ
if (index !== -1) {}const index = array.findIndex(element => element > 10);
// โ
if (index < 0) {}
// โ
if (index === -1) {}const index = array.findLastIndex(element => element > 10);
// โ
if (index < 0) {}
// โ
if (index === -1) {}File: docs/rules/consistent-function-scoping.md
consistent-function-scoping
๐ Move function definitions to the highest possible scope.
๐ผ๐ซ This rule is enabled in the โ
recommended config. This rule is disabled in the โ๏ธ unopinionated config.
A function definition should be placed as close to the top-level scope as possible without breaking its captured values. This improves readability, directly improves performance and allows JavaScript engines to better optimize performance.
Examples
// โ
export function doFoo(foo) {
// Does not capture anything from the scope, can be moved to the outer scope
function doBar(bar) {
return bar === 'bar';
}
return doBar;
}// โ
function doBar(bar) {
return bar === 'bar';
}
export function doFoo(foo) {
return doBar;
}// โ
function doFoo() {
// Does not capture anything from the scope, can be moved to the outer scope
return bar => bar === 'bar';
}// โ
const doBar = bar => bar === 'bar';
function doFoo() {
return doBar;
}// Arrow functions in return statements are also flagged
// โ
export function someAction() {
return dispatch => dispatch({type: 'SOME_TYPE'});
}// Arrow functions in return statements are also flagged
// โ
const handleDispatch = dispatch => dispatch({type: 'SOME_TYPE'});
export function someAction() {
return handleDispatch;
}// โ
function doFoo(foo) {
const doBar = bar => {
return bar === 'bar';
};
}// โ
const doBar = bar => {
return bar === 'bar';
};
function doFoo(foo) {}// โ
export function doFoo(foo) {
function doBar(bar) {
return bar === 'bar' && foo.doBar(bar);
}
return doBar;
}
const doBar = bar => bar === 'bar';
export function doFoo() {
return doBar;
}Options
checkArrowFunctions
Type: boolean
Default: true
Pass "checkArrowFunctions": false to disable linting of arrow functions.
Limitations
This rule does not detect or remove extraneous code blocks inside of functions:
function doFoo(foo) {
{
function doBar(bar) {
return bar;
}
}
return foo;
}Immediately invoked function expressions (IIFE) are ignored:
(function () {
function doFoo(bar) {
return bar;
}
})();Built-in Hooks in React are ignored:
useEffect(() => {
async function getItems() {}
getItems();
}, [])Functions inside jest.mock() factories are ignored because Jest restricts those factories from referencing out-of-scope variables:
jest.mock('module', () => {
function createMock() {
return 'mock';
}
return createMock;
});File: docs/rules/custom-error-definition.md
custom-error-definition
๐ Enforce correct Error subclassing.
๐ซ This rule is disabled in the following configs: โ
recommended, โ๏ธ unopinionated.
๐ง This rule is automatically fixable by the --fix CLI option.
Enforces a consistent way of defining Error subclasses. It works with superclasses whose names match the rule's *Error naming pattern.
When a named error constructor accepts a message, it should also accept options and pass it to super() so native Error#cause is preserved. This convention is only enforced for native error bases that accept ErrorOptions as their second parameter. AggregateError accepts ErrorOptions as its third parameter, while SuppressedError does not accept ErrorOptions, so neither uses this convention.
Custom error base classes may use different constructor parameters, so the rule does not enforce the native ErrorOptions convention for them.
// โ
class UserNotFoundError extends GraphQLError {
constructor(userId) {
super(`User "${userId}" does not exist`, {extensions: {code: 'NOT_FOUND'}});
this.name = 'UserNotFoundError';
}
}Examples
// โ
class CustomError extends Error {
constructor(message, options) {
super(message, options);
// The `this.message` assignment is useless as it's already set via the `super()` call.
this.message = message;
this.name = 'CustomError';
}
}
// โ
class CustomError extends Error {
constructor(message, options) {
super(undefined, options);
// Pass the error message to `super()` instead of setting `this.message`.
this.message = message;
this.name = 'CustomError';
}
}
// โ
class CustomError extends Error {
constructor(message, options) {
super(message, options);
// No `name` property set. The name property is needed so the
// error shows up as `[CustomError: foo]` and not `[Error: foo]`.
}
}
// โ
class CustomError extends Error {
constructor(message, options) {
super(message, options);
// Use a string literal to set the `name` property as it will not change after minifying.
this.name = this.constructor.name;
}
}
// โ
class CustomError extends Error {
constructor(message, options) {
super(message, options);
// The `name` property should be set to the class name.
this.name = 'MyError';
}
}
// โ
class CustomError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'CustomError';
}
}// โ
// The class name should be capitalized and end with `Error`.
class foo extends Error {
constructor(message, options) {
super(message, options);
this.name = 'foo';
}
}
// โ
class FooError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'FooError';
}
}// โ
class CustomError extends Error {
constructor(message, details) {
super(message);
this.details = details;
this.name = 'CustomError';
}
}
// โ
class CustomError extends Error {
constructor(message, options) {
super(message, options);
this.details = options?.details;
this.name = 'CustomError';
}
}// โ
class CustomError extends Error {
constructor() {
super('My custom error');
this.name = 'CustomError';
}
}// โ
// The message is hard-coded and the error options are passed to `super()` inline, so no `options` parameter is needed.
class CustomError extends Error {
constructor(cause) {
super('My custom error', {cause});
this.name = 'CustomError';
}
}// โ
class CustomError extends TypeError {
constructor() {
super();
this.name = 'CustomError';
}
}// โ
class CustomError extends Error {
name = 'CustomError';
}When defining a custom message accessor, don't pass the message to super() as it would shadow the accessor with an own message property. Store the message somewhere else instead.
// โ
class CustomError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'CustomError';
}
get message() {
return 'Custom message';
}
}
// โ
class CustomError extends Error {
#message;
constructor(message, options) {
super(undefined, options);
this.#message = message;
this.name = 'CustomError';
}
get message() {
return this.#message;
}
}