Unicorn
Modernization and style rules from eslint-plugin-unicorn, spanning array iteration, string and regex idioms, Node.js APIs, error handling, module syntax, DOM APIs, and code shape. Rewrites legacy patterns into their modern counterparts (for...of over forEach, Array#flatMap over map().flat(), String#replaceAll over a global-regex replace, Math.trunc over | 0), forbids known anti-patterns (null literals, abusive eslint-disable, new Buffer, process.exit, instanceof Array), and pins a consistent style for things ESLint core and TypeScript leave underspecified (filename case, numeric separators, catch-binding names, expiring TODOs, escape-sequence case, switch-case braces). Pure-AST; no checker dependencies.
Source: eslint-plugin-unicorn (MIT).
unicorn/better-regex: Rewrite regex literals into shorter, consistent, and safer form (character-class shorthands, redundant ranges).unicorn/catch-error-name: Enforce a canonical parameter name (error) incatchclauses.unicorn/consistent-assert: Enforce consistent assertion style when usingnode:assert.unicorn/consistent-date-clone: Prefer passing aDatedirectly to theDateconstructor when cloning, not+dateordate.getTime().unicorn/consistent-destructuring: Once a property is destructured from an object, require subsequent reads to use the destructured binding.unicorn/consistent-empty-array-spread: Require both branches of a ternary spread inside an array literal to be array-typed.unicorn/consistent-existence-index-check: Enforce a consistent comparison form (< 0vs=== -1,>= 0vs!== -1) forindexOf/findIndexexistence checks.unicorn/consistent-function-scoping: Hoist function declarations to the highest scope that does not capture any outer variables.unicorn/consistent-template-literal-escape: Enforce a consistent style (always\${or always$\{) when escaping${in template literals.unicorn/custom-error-definition: Require user-definedErrorsubclasses to setname, callsuper(message), and assign their stack correctly.unicorn/empty-brace-spaces: Reject whitespace inside empty{}braces.unicorn/error-message: Require a non-emptymessageargument when constructing a built-inError.unicorn/escape-case: Require consistent case for escape sequences (\xA9over\xa9,µoverµ).unicorn/expiring-todo-comments: Require everyTODO/FIXME/XXXcomment to declare an expiration date or package version.unicorn/explicit-length-check: Require explicit comparison of.length/.sizeinstead of relying on truthy coercion.unicorn/filename-case: Enforce a single case style (kebab / camel / snake / pascal) for source filenames.unicorn/import-style: Restrict each module’s allowed import styles (named only, default only, namespace only).unicorn/isolated-functions: Reject references to outer-scope variables inside functions marked as isolated (e.g., the body of a web worker).unicorn/new-for-builtins: Requirenewwhen calling builtin constructors likeError,Map,Set,Date, and forbidnewon primitive wrappers likeString,Number,Boolean.unicorn/no-abusive-eslint-disable: Require everyeslint-disable*directive to name the rules it disables.unicorn/no-accessor-recursion: Reject recursive reads onthis.<prop>inside the getter / setter for<prop>.unicorn/no-anonymous-default-export: Require a name on every default-exported function, class, or object.unicorn/no-array-callback-reference: Reject passing a function reference directly as the callback tomap/filter/forEach/ etc., which silently leaks extra index/array arguments.unicorn/no-array-for-each: Preferfor...ofoverArray.prototype.forEach.unicorn/no-array-method-this-argument: Reject the secondthisArgargument to array methods; use an explicit closure instead.unicorn/no-array-reduce: RejectArray#reduce/Array#reduceRightin favor of explicit loops or other helpers.unicorn/no-array-reverse: PreferArray#toReversedover the mutatingArray#reverse.unicorn/no-array-sort: PreferArray#toSortedover the mutatingArray#sort.unicorn/no-await-expression-member: Reject member access on anawaitexpression without parens; require(await x).y.unicorn/no-await-in-promise-methods: Rejectawaitinside arrays passed toPromise.all/Promise.allSettled/Promise.race/Promise.any. The awaits serialize the calls.unicorn/no-console-spaces: Reject leading or trailing spaces in arguments toconsole.logand friends,consolealready inserts spaces between arguments.unicorn/no-document-cookie: Reject direct reads or assignments todocument.cookie; use the Cookie Store API or a wrapper.unicorn/no-empty-file: Reject source files whose only content is whitespace and/or comments.unicorn/no-for-loop: Preferfor...ofover index-basedforloops over arrays.unicorn/no-hex-escape: Prefer Unicode escape (©) over hexadecimal escape (\xA9).unicorn/no-immediate-mutation: Reject mutating a value on the same expression that produces it ([...x].push(y)); separate the construction and the mutation.unicorn/no-instanceof-builtins: Rejectinstanceof Array,instanceof Error,instanceof Map, etc.. They fail across realms and for subclasses.unicorn/no-invalid-fetch-options: Reject GET / HEADfetch()calls that also set a requestbody, which throws at runtime.unicorn/no-invalid-remove-event-listener: RejectremoveEventListenercalls whose handler argument is a fresh function reference and therefore matches no registered listener.unicorn/no-keyword-prefix: Reject identifiers that start with a reserved word (newFoo,classBar).unicorn/no-lonely-if: Rejectifas the only statement inside anelseblock; useelse ifinstead.unicorn/no-magic-array-flat-depth: Reject magic-number depth arguments toArray#flat; requireInfinityor a named constant.unicorn/no-named-default: Reject re-importing or re-exporting a default binding under a name that differs from the upstream binding.unicorn/no-negated-condition: Reject negated conditions inif/elseand ternaries when the positive form is shorter.unicorn/no-negation-in-equality-check: Reject!a === b; requirea !== bor!(a === b).unicorn/no-nested-ternary: Reject ternaries nested inside other ternaries.unicorn/no-new-array: Reject thenew Array(...)constructor; use array literals orArray.from/Array.of.unicorn/no-new-buffer: Reject the deprecatednew Buffer()constructor; useBuffer.fromorBuffer.alloc.unicorn/no-null: Reject thenullliteral in favor ofundefined.unicorn/no-object-as-default-parameter: Reject inline object literals as default values for function parameters.unicorn/no-process-exit: Rejectprocess.exit(); throw or return a non-zero status instead.unicorn/no-single-promise-in-promise-methods: RejectPromise.all/Promise.race/ etc. Called with a single-element array; the wrapper is redundant.unicorn/no-static-only-class: Reject classes whose every member isstatic; use a plain module-level namespace instead.unicorn/no-thenable: Reject defining a property namedthenon objects, modules, or classes,awaitand Promise resolution accidentally invoke it.unicorn/no-this-assignment: Rejectconst self = thisand similar aliases; capture via arrow functions instead.unicorn/no-typeof-undefined: Rejecttypeof x === "undefined"; compare againstundefineddirectly.unicorn/no-unnecessary-array-flat-depth: Reject1as the explicit depth argument ofArray#flat; the default is already1.unicorn/no-unnecessary-array-splice-count: Reject.length/Infinityas the deleteCount argument tosplice/toSpliced; omit it to delete to the end.unicorn/no-unnecessary-await: Rejectawaiton non-thenable expressions.unicorn/no-unnecessary-polyfills: Reject polyfill imports for APIs already available in the project’s targeted Node / browser baseline.unicorn/no-unnecessary-slice-end: Reject.length/Infinityas the end argument toslice; omit it to slice to the end.unicorn/no-unreadable-array-destructuring: Reject destructuring patterns with long hole runs ([,,,,a]); use a named index instead.unicorn/no-unreadable-iife: Reject IIFEs whose nesting (multiple parens, arrow IIFE arguments) is hard to read.unicorn/no-unused-properties: Reject object properties that are never read after definition.unicorn/no-useless-collection-argument: Reject useless initializer arguments (new Set(),new Map([]),new Set(undefined)) on collection constructors.unicorn/no-useless-error-capture-stack-trace: RejectError.captureStackTrace(this, constructor)when the surrounding subclass relies on the defaultErrorcapture.unicorn/no-useless-fallback-in-spread: Reject...(x ?? {})and similar fallbacks when spreading; the spread ofnull/undefinedis already a no-op.unicorn/no-useless-iterator-to-array: Reject[...iterator]/Array.from(iterator)when the iterator can be consumed directly (e.g., insidefor...of).unicorn/no-useless-length-check: Rejectarr.lengthchecks that the iteration method itself already handles.unicorn/no-useless-promise-resolve-reject: Rejectreturn Promise.resolve(x)/return Promise.reject(e)insideasyncfunctions,return xandthrow ework identically.unicorn/no-useless-spread: Reject spreading a single iterable into a new collection of the same kind ([...arr],{...obj}) when the original would suffice.unicorn/no-useless-switch-case: Rejectcaseclauses with an empty body that immediately precede adefaultwhose body executes for them.unicorn/no-useless-undefined: Reject explicitundefinedreturns, default initializers, and arguments where the omission has the same meaning.unicorn/no-zero-fractions: Reject1.0/1./.5e0in favor of1,1, and0.5.unicorn/number-literal-case: Enforce one consistent case for the prefix and digits of hex / binary / octal literals (0xFFover0xff).unicorn/numeric-separators-style: Enforce_separator grouping (every 3 digits for decimal, every 4 for hex) in numeric literals.unicorn/prefer-add-event-listener: PreferaddEventListener/removeEventListenerover assigning toon*properties.unicorn/prefer-array-find: PreferArray#find/Array#findLastoverfilter(...)[0]/filter(...).at(-1).unicorn/prefer-array-flat: PreferArray#flatover legacy flattening idioms ([].concat(...arrs),reducewithconcat).unicorn/prefer-array-flat-map: PreferArray#flatMapovermap(...).flat().unicorn/prefer-array-index-of: PreferindexOf/lastIndexOfoverfindIndex/findLastIndexwhen matching by===.unicorn/prefer-array-some: PreferArray#someoverfilter(...).length > 0,find(...) !== undefined, and similar shapes.unicorn/prefer-at: PreferArray#at/String#atover index arithmetic andcharAt.unicorn/prefer-bigint-literals: Prefer1noverBigInt(1)andBigInt("1").unicorn/prefer-blob-reading-methods: PreferBlob#arrayBuffer()/Blob#text()overFileReader#readAsArrayBuffer/readAsText.unicorn/prefer-class-fields: Prefer class field declarations over constructor assignments tothis.field = value.unicorn/prefer-classlist-toggle: PreferElement#classList.toggle(name, condition)over manualadd/removebranches.unicorn/prefer-code-point: PreferString#codePointAt/String.fromCodePointovercharCodeAt/fromCharCode.unicorn/prefer-date-now: PreferDate.now()overnew Date().getTime()/+new Date().unicorn/prefer-default-parameters: Prefer default parameter syntax overx = x ?? defaultreassignments inside the function body.unicorn/prefer-dom-node-append: PreferNode#appendoverNode#appendChild.unicorn/prefer-dom-node-dataset: PreferElement#datasetovergetAttribute/setAttributefordata-*attributes.unicorn/prefer-dom-node-remove: PreferChildNode#removeoverparent.removeChild(child).unicorn/prefer-dom-node-text-content: PreferNode#textContentoverHTMLElement#innerText.unicorn/prefer-event-target: PreferEventTargetover Node’sEventEmitterwhen the code is shared between Node and the browser.unicorn/prefer-export-from: Preferexport ... fromover importing-then-re-exporting in two statements.unicorn/prefer-global-this: PreferglobalThisoverwindow,self, andglobal.unicorn/prefer-import-meta-properties: Preferimport.meta.dirname/import.meta.filenameoverfileURLToPathworkarounds.unicorn/prefer-includes: PreferString#includes/Array#includesoverindexOf(...) !== -1andsome(x => x === target).unicorn/prefer-json-parse-buffer: Prefer passing aBufferdirectly toJSON.parse(Node 21+) instead of decoding to a string first.unicorn/prefer-keyboard-event-key: PreferKeyboardEvent#keyover the deprecatedKeyboardEvent#keyCode/charCode/which.unicorn/prefer-logical-operator-over-ternary: Prefera || b/a ?? bover the equivalent ternarya ? a : b.unicorn/prefer-math-min-max: PreferMath.min/Math.maxover ternaries computing the same value.unicorn/prefer-math-trunc: PreferMath.truncover~~x/x | 0for integer truncation.unicorn/prefer-modern-dom-apis: Preferbefore/after/replaceWithoverinsertBefore/replaceChild/insertAdjacentText.unicorn/prefer-modern-math-apis: PreferMath.log10/Math.hypot/Math.log2/Math.cbrtover their legacy approximations.unicorn/prefer-module: Prefer ES modules (import/export) over CommonJS (require/module.exports/__dirname/__filename).unicorn/prefer-native-coercion-functions: Prefer the bareString/Number/Boolean/BigIntfunctions overx => String(x)arrow wrappers.unicorn/prefer-negative-index: Prefer negative-index lookups (arr.at(-1),arr.slice(-2)) overarr.length - 1/arr.length - 2arithmetic.unicorn/prefer-node-protocol: Prefernode:fs/node:path/ etc. Over the bare Node builtin specifier.unicorn/prefer-number-properties: PreferNumber.isNaN/Number.parseInt/Number.NaNover their global counterparts.unicorn/prefer-object-from-entries: PreferObject.fromEntriesoverreduce-into-object patterns.unicorn/prefer-optional-catch-binding: Prefercatch { ... }overcatch (e) { ... }wheneis unused.unicorn/prefer-prototype-methods: Prefer borrowing prototype methods (Array.prototype.slice.call) over[].slice.callempty-instance lookups.unicorn/prefer-query-selector: PreferDocument#querySelectorovergetElementById,getElementsByClassName, andgetElementsByTagName.unicorn/prefer-reflect-apply: PreferReflect.apply(fn, thisArg, args)overFunction.prototype.apply.call(fn, thisArg, args).unicorn/prefer-regexp-test: PreferRegExp#testoverString#match/RegExp#execwhen only a boolean is needed.unicorn/prefer-response-static-json: PreferResponse.json(value)overnew Response(JSON.stringify(value), { headers: { "content-type": "application/json" } }).unicorn/prefer-set-has: PreferSet#hasoverArray#includesfor repeated membership lookups against a constant collection.unicorn/prefer-set-size: PreferSet#sizeover[...set].lengthandArray.from(set).length.unicorn/prefer-simple-condition-first: Prefer the simpler operand on the left of&&/||so the short-circuit reads in evaluation order.unicorn/prefer-single-call: Prefer a singlepush/unshift/classList.add/addEventListenerwith multiple arguments over consecutive single-argument calls.unicorn/prefer-spread: Prefer spread ([...arr],[...str]) overArray.from,Array.prototype.slice.call,concat([]), andsplit('').unicorn/prefer-string-raw: PreferString.rawfor path literals and other strings that would otherwise need backslash escapes.unicorn/prefer-string-replace-all: PreferString#replaceAll(literal, replacement)overreplace(/literal/g, replacement).unicorn/prefer-string-slice: PreferString#sliceover the deprecatedsubstr/substring.unicorn/prefer-string-starts-ends-with: PreferString#startsWith/String#endsWithover equivalentRegExp#testand slice-then-compare idioms.unicorn/prefer-string-trim-start-end: PreferString#trimStart/String#trimEndover the deprecatedtrimLeft/trimRight.unicorn/prefer-structured-clone: PreferstructuredClone(x)overJSON.parse(JSON.stringify(x))for deep cloning.unicorn/prefer-switch: Preferswitchover chains of three or moreelse ifclauses comparing the same discriminant.unicorn/prefer-ternary: Prefer a ternary overif/elsewhose two branches differ only in the right-hand side of a common assignment,return, orthrow.unicorn/prefer-top-level-await: Prefer top-levelawaitover.then/ IIFE wrappers in ES modules.unicorn/prefer-type-error: Require throwingTypeError(not a bareError) when the surroundingifis a runtime type check.unicorn/prevent-abbreviations: Reject common identifier abbreviations (btn,arr,idx) and replace them with their long forms.unicorn/relative-url-style: Enforce a single style (always leading./vs. Never) for relative URLs passed tonew URL.unicorn/require-array-join-separator: Require an explicit separator argument toArray#joininstead of relying on the default",".unicorn/require-module-attributes: Require non-emptywith/assertoptions onimport/exportstatements that use them at all.unicorn/require-module-specifiers: Require a non-empty specifier list on everyimport/exportstatement.unicorn/require-number-to-fixed-digits-argument: Require an explicit digits argument toNumber#toFixed.unicorn/require-post-message-target-origin: Require an explicittargetOriginargument towindow.postMessage.unicorn/string-content: Enforce or replace configured string-content patterns (e.g., curly quotes for straight ones).unicorn/switch-case-braces: Enforce a consistent presence/absence of{}braces aroundcaseclauses insideswitch.unicorn/switch-case-break-position: Enforce a consistent position forbreak(orreturn/throw) insidecaseclauses.unicorn/template-indent: Re-indent the body of tagged template literals (html,gql,sql) to the indentation of the opening backtick.unicorn/text-encoding-identifier-case: Enforce a canonical case for text-encoding identifiers,"utf-8"(not"UTF-8"/"utf8").unicorn/throw-new-error: Requirethrow new Error(...)overthrow Error(...).
Last updated on