accessor-pairs
array-bracket-newline
multiline
and minItems
, ensuring that the enforcement of line breaks is meaningful and context-aware, rather than applying a one-size-fits-all approach that might not be suitable for all scenarios.array-bracket-spacing
array-callback-return
return
statements in callbacks of array methods.map()
, .filter()
, etc., include a return
statement, preventing silent failures or unexpected behaviors when developers forget to return a value, especially crucial for methods that are expected to produce a new array based on the return value from the callback.
allowImplicit
, checkForEach
, and allowVoid
allows for tailored enforcement, accommodating different coding styles or project requirements. For instance, checkForEach
can enforce stylistic consistency by disallowing returns in forEach
callbacks, where they are meaningless.
void
to explicitly mark callbacks that don’t return anything) directly in the linting warnings/errors provides immediate, actionable guidance to developers, helping them correct mistakes on-the-fly without breaking their workflow.
array-element-newline
multiline
, minItems
), allowing teams or projects to tailor the rule to match their coding style guidelines, thus maintaining codebase uniformity.arrow-body-style
return
keyword are unnecessary for single-return arrow functions, thereby promoting a cleaner, more concise syntax that can improve the ease of understanding and working with the code.arrow-parens
arrow-spacing
const add = (a,b)=>a+b;
to the more readable const add = (a, b) => a + b;
.block-scoped-var
i
is accessed outside the loop.let
and const
) over function-scoped var
, aligning with modern JavaScript best practices and helping to avoid common pitfalls associated with var
’s function scope.i
outside its loop could lead to unexpected behaviors or errors if i
was inadvertently changed elsewhere.block-spacing
BlockStatement
, StaticBlock
, and SwitchStatement
, ensuring comprehensive coverage across various JavaScript code structures. This holistic approach helps maintain consistent spacing not just in simple block statements but also in more complex constructs, enhancing overall code quality.brace-style
callback-return
return
statements after callbackscamelcase
allow
option) and controlling the enforcement on properties, destructuring, and import/export identifiers. This flexibility allows teams to adapt the rule according to their specific needs or existing code conventions, facilitating a smoother integration with minimal disruption to existing code.
capitalized-comments
class-methods-use-this
this
this
keyword, ensuring that methods are properly utilizing class context and state. This reinforces object-oriented design principles where methods should operate on the object’s data.static
methods) or have special roles in class behavior (constructors), which might not necessitate the use of this
. This built-in exemption reduces false positives and focuses the rule on standard instance methods where this
is expected to be used.comma-dangle
comma-spacing
comma-style
complexity
computed-property-spacing
consistent-return
return
statements to either always or never specify valuestreatUndefinedAsUnspecified
allows for flexibility in treating returns that explicitly return undefined
as unspecified, accommodating different coding styles while still enforcing overall consistency in the codebase, which can be beneficial in projects with multiple contributors.consistent-this
this
) is stored in a variable, it is done using a consistent naming convention across the codebase, thereby reducing confusion and improving readability.this
, but instead is either not assigned or assigned to a different value.this
, promoting more organized and professional code practices.constructor-super
super()
calls in constructorssuper()
is called in derived classes. This adherence ensures that the base class constructor is properly executed before executing the derived class’s constructor logic, preventing reference errors and uninitialized state within the derived instance.
super()
may be conditionally called or omitted. By analyzing all code paths, it helps identify logical errors early in the development process, ensuring that derived classes are correctly set up in every possible execution path.
super()
in scenarios with conditional branches and loops, this rule helps avoid subtle bugs that could arise from complex constructor logic. It ensures that super()
is not just called but is called in a manner consistent with the constructor’s intended flow, including scenarios where loops or conditional paths might inadvertently skip the necessary base class initialization.
curly
multi
, multi-line
, multi-or-nest
, consistent
), allowing teams to adopt a brace style that suits their specific preferences or the nuances of their project. This flexibility ensures that the rule can be adapted to different coding conventions while still providing the benefits of consistency and clarity in control statements.default-case-last
default
clause is last improves the readability of switch
statements, making the structure more predictable and thus easier to understand at a glance. This aligns with common coding conventions that advocate for a consistent ordering of cases.default
clause, which could lead to unexpected behavior if developers assume all case clauses are evaluated before the default
.default
clause to always be last simplifies the addition of new case clauses in the future, as developers won’t have to worry about accidentally inserting them after the default
, potentially causing unreachable code.switch
statements, which can improve the efficiency of code reviews and onboarding new team members.default-case
default
cases in switch
statementsswitch
statements by requiring a default
case, thus preventing runtime errors from unhandled cases. This can be especially crucial in situations where the switch statement handles inputs or conditions that might change or expand over time.default
case, developers are encouraged to consider and handle potential unexpected values, leading to more robust and error-resistant code. This can be particularly beneficial in large projects with multiple contributors where the exhaustive handling of all possible cases might be overlooked.switch
cases. Including a default
case or an explanatory comment where a default
case might be intentionally omitted serves as documentation within the code itself.commentPattern
option, providing teams flexibility in adhering to the rule while accommodating cases where a default
case might be purposely excluded. This can be useful in scenarios where the logic for handling unanticipated values is documented elsewhere or when the lack of a default
case is a deliberate choice supported by comments that match the provided pattern.default-param-last
default-param-last
ensures that default parameters in functions are declared last, which maintains consistency in function signatures across the codebase. This consistency makes it easier for developers to understand the function’s expected behavior and how to properly call it, especially when swiftly scanning through code or when the function is part of a public API.
default-param-last
rule can facilitate better code design practices by encouraging developers to think more about the ordering of function parameters and their defaults. This conscious structuring of function signatures can lead to more thoughtfully designed interfaces that are intuitive to use and easier to maintain over time.
dot-location
dot-notation
object.property
than object['property']
, especially for those new to JavaScript. This rule ensures a consistent and cleaner codebase by preferring the more readable syntax whenever possible.
eol-last
eqeqeq
===
and !==
===
and !==
), preventing unintended type coercion that can occur with abstract equality checks (==
and !=
). This enhances code reliability and predictability in comparisons.
null
checks separately, it offers flexibility to cater to various coding standards and practices, enabling teams to adopt strict equality checks while making exceptions as needed.
typeof
comparisons. This feature assists developers by reducing manual refactoring effort and accelerating the process of adopting strict equality checks.
typeof
operations and null
comparisons, acknowledging common patterns where developers might intentionally use abstract equality. This thoughtful inclusion reduces false positives in scenarios where abstract equality might be deemed acceptable or necessary by some developers.
for-direction
i--
) when it should increase to reach a termination condition (i < 10
) could cause a loop to never terminate.
++
, --
) and assignment expressions (+=
, -=
) within “for” loops, ensuring that they are correctly contributing towards reaching the loop’s termination condition rather than moving away from it.
func-call-spacing
func-name-matching
func-names
function
expressionsfunc-style
function
declarations or expressionsThisExpression
usage within function blocks lets teams decide more judiciously on enforcing function declarations over expressions or vice versa based on how this
is used. This is particularly useful for older JavaScript where arrow functions and their lexical this
binding aren’t available, ensuring that functions are defined in a style that best suits their usage context and the surrounding lexical scope.
function-call-argument-newline
function-paren-newline
minItems
), allowing teams to establish a threshold that triggers this formatting rule, which is helpful in maintaining a concise code style for smaller function calls while still applying best practices for larger ones.multiline
, multiline-arguments
, consistent
), offering flexibility to cater to various coding styles or preferences within a team, thus promoting uniformity without enforcing a one-size-fits-all approach.generator-star-spacing
*
operators in generator functions*
in generator functions, which can improve code readability and maintainability by adhering to a project’s or team’s coding standards.*
, catering to different team or project style guidelines without enforcing a single style.getter-return
return
statements in gettersglobal-require
require()
calls to be placed at top-level module scoperequire()
calls are at the top level, making it easier to locate dependencies and understand the module’s dependencies at a glance.require()
calls by establishing a pattern where modules are loaded once at the beginning, improving the performance and reliability of the application.grouped-accessor-pairs
guard-for-in
for-in
loops to include an if
statementfor-in
loops are only iterating over the object’s own properties and not over the inherited properties from the prototype chain, which can prevent potential bugs and unexpected behavior in the application. It requires the use of an if
statement, such as if (obj.hasOwnProperty(prop))
, to check if the property belongs to the object directly.
if
statement inside for-in
loops, the rule promotes writing more secure and optimized code. It helps in preventing the execution of code for unintended properties, which might not only lead to incorrect results but could also introduce security vulnerabilities, especially when dealing with objects that might come from untrusted sources.
handle-callback-err
err
. By enforcing an inspection of this err
parameter, it helps ensure that asynchronous operations are robustly designed to handle failures, which are common in I/O operations or network requests.err
directly but follow a project’s naming conventions. It accounts for flexibility in coding styles by permitting the use of regular expressions to match the error parameter’s name, ensuring that developers are not forced into a naming convention that does not fit their project’s guidelines.id-blacklist
reportedNodes
set to track already reported nodes based on their range, ensuring that each naming violation is reported exactly once, even if the same identifier appears in multiple contexts.id-denylist
id-length
id-match
implicit-arrow-linebreak
indent-legacy
no-mixed-spaces-and-tabs
rule), it promotes consistency in using either spaces or tabs for indentation within a project, thus preventing errors related to mixed indentation.indent
index
init-declarations
undefined
values.ignoreForLoopInit
option, acknowledging the unique scenarios where variables like loop counters are initialized within the loop construct itself, thus offering flexibility and avoiding unnecessary warnings for common patterns.jsx-quotes
key-spacing
keyword-spacing
line-comment-position
position
, ignorePattern
, and applyDefaultIgnorePatterns
, it accommodates different coding style preferences. Teams can configure the rule to match their specific standards, ensuring that everyone adheres to the same guidelines without limiting them to a one-size-fits-all approach.linebreak-style
\n
) or Windows-style (\r\n
), as per the developer’s or team’s convention specified in the ESLint rule. This uniformity reduces the chance of merge conflicts due to linebreak differences.lines-around-comment
lines-around-directive
lines-between-class-members
logical-assignment-operators
||=
, ??=
) which express the intent more clearly and concisely than traditional assignment combined with logical operations. This can make it easier for developers to understand at a glance what the code is intended to do, especially in cases where a value should only be assigned if it is currently null, undefined, or falsy.
foo = foo || bar;
versus foo ||= bar;
). By encouraging the shorthand syntax, this rule minimizes the chances of accidentally creating bugs through incorrect assignments or comparisons.
??
with ||
/&&
, or when dealing with potentially problematic code constructs such as with statements or strict mode considerations.
max-classes-per-file
max-depth
max-len
ignorePattern
provides exceptional customizability for projects with unique needs. This means that lines containing specific patterns, perhaps related to domain-specific terms, generated code, or other exceptions, can be whitelisted to bypass the max-length rule, allowing developers to tailor the rule precisely to their project’s requirements.max-lines-per-function
max-lines
max-nested-callbacks
max-params
max-statements-per-line
max-statements
multiline-comment-style
multiline-ternary
new-cap
new
keyword, preventing misuse.new
keyword can lead to unexpected behavior or errors. By adhering to this naming convention, such mistakes are more easily spotted during code review or by static analysis tools.new-parens
newline-after-var
newline-before-return
return
statementsreturn
statement from the preceding block of code, making it easier for developers to quickly identify where functions or blocks of code end and return a value.return
statements becomes a project-wide standard that all developers follow, leading to a more uniform codebase.return
statements that may have been mistakenly added without proper separation, potentially indicating a logical error or a piece of code that requires further review or refactoring.newline-per-chained-call
ignoreChainWithDepth
option to meet their specific needs, tailoring the rule enforcement to match preferred coding guidelines.no-alert
alert
, confirm
, and prompt
alert
, confirm
, and prompt
can be disruptive and create a poor user experience, especially on modern web applications. Eliminating these in favor of more user-friendly UI messages or modals can lead to a smoother interaction for the end user.
alert
, confirm
, and prompt
encourages developers to utilize more sophisticated and customizable UI components that are in line with modern web development practices, leading to richer and more interactive web applications.
alert
with console.log
for debugging, or even better, implementing structured logging mechanisms, can significantly improve the debugging process. It makes tracking application behavior and identifying issues easier without interrupting the user flow.
no-array-constructor
Array
constructors[]
) instead of the Array
constructor. This makes the code easier to understand, especially for those new to JavaScript or coming from other programming languages.
Array
constructor to create arrays. For example, new Array(5)
creates an array with a length of 5, not an array containing the number 5, which can be counter-intuitive.
no-async-promise-executor
no-await-in-loop
await
inside of loopsno-await-in-loop
helps in identifying performance pitfalls in asynchronous code where await
within loops could lead to sequential execution of asynchronous operations, rather than parallel execution. This is significant because it directly affects the speed and efficiency of tasks that could otherwise be carried out concurrently.
await
inside loops, this ESLint rule encourages developers to refactor their code towards patterns that leverage concurrent execution of promises, such as using Promise.all
. This leads to more efficient code execution, as asynchronous tasks can run in parallel, reducing the overall time taken when dealing with multiple asynchronous operations.
await
in a loop executes each iteration’s asynchronous operation one after the other, rather than all at once. This rule makes it explicit that such a pattern is not recommended, which is especially beneficial in scenarios where performance optimization is critical.
Promise.all
for handling multiple fetch requests demonstrates an explicit intent to execute multiple promises concurrently, which is a pattern that can significantly improve the responsiveness and efficiency of web applications or back-end services.
no-bitwise
Math.floor
) and language features (e.g., destructuring assignment for swapping variables), which tend to be more self-explanatory and aligned with the language’s higher-level abstractions.
no-buffer-constructor
Buffer()
constructorBuffer()
constructor either directly or with the new
keyword, which can lead to inconsistent or unpredictable results due to changes in the Buffer API in different versions of Node.js. Ensuring developers use the recommended methods such as Buffer.from()
, Buffer.alloc()
, or Buffer.allocUnsafe()
contributes to more stable and secure code.
Buffer.from()
and Buffer.alloc()
. Buffer.alloc()
initializes new buffers to zero, reducing cases where sensitive information may inadvertently be exposed through uninitialized memory segments. This directly ties to improving the security posture of applications by helping prevent vulnerabilities related to the exposure of memory content.
Buffer()
constructor due to security, usability, and efficiency concerns. As Node.js evolves, reliance on deprecated features could complicate upgrading to newer versions, thus adherence to this rule simplifies maintenance and upgrades.
Buffer.allocUnsafe()
) and more readable code (Buffer.from()
for creating buffers from existing data). This duality of improving performance while also enhancing code clarity and safety underscores the rule’s practical importance in modern Node.js development practices.
no-caller
arguments.caller
or arguments.callee
arguments.caller
and arguments.callee
, which are both deprecated and forbidden in strict mode, thus promoting the use of modern JavaScript functionalities and ensuring code compatibility with strict mode.arguments.caller
and arguments.callee
can lead to potential security vulnerabilities by exposing stack trace details or allowing function calls in unintended ways.arguments.callee
, makes the code more readable, easier to debug, and adherent to modern JavaScript standards.arguments.callee
can prevent certain optimizations by JavaScript engines due to the required dynamic scope resolution. Avoiding its use, as enforced by this rule, can contribute to better overall performance of the code.no-case-declarations
let
or const
directly within a case clause. Since let
and const
have block-level scope, declaring them without a block in a case clause could lead to unexpected behavior or scope leakage.let
or const
are correctly scoped to the case, preventing them from being accessible in other cases.var
declarations are hoisted to the top of their function scope, but let
and const
are not. This rule ensures that when developers use let
or const
in case clauses, they are explicitly aware of the block scope, reducing the chance of redeclaration or hoisting issues.no-catch-shadow
catch
clause parameters from shadowing variables in the outer scopeno-class-assign
no-compare-neg-zero
Object.is
for checking the presence of -0, which is the correct method to distinguish -0 from 0. This educates developers on the appropriate way to perform such checks and promotes writing code that behaves as expected without unintended type coercion issues.==
, ===
, >
, and <
can introduce subtle bugs due to how JavaScript handles -0 and 0. By disallowing these comparisons, the rule helps prevent potential bugs in the logic of applications that could be hard to diagnose and might lead to incorrect behavior or outcomes.no-cond-assign
=
instead of ==
or ===
in an if
statement condition can unintentionally assign a new value rather than compare values, leading to conditions that are always true and potentially unnoticed logic errors.
"except-parens"
) that allows for assignments within parentheses in conditional expressions. This flexibility allows teams to adopt a coding style that permits intentional assignments in conditionals while still protecting against the common mistake of accidental assignments. This can be helpful in situations where an assignment within a conditional is genuinely needed and is a deliberate part of the program logic.
no-confusing-arrow
a => a > 5 ? "Yes" : "No";
might be mistaken at a glance for a comparison operation rather than an arrow function that returns the result of a ternary operation. This increases code readability and reduces the likelihood of misinterpretation.
allowParens
and onlyOneSimpleParam
give developers flexibility in enforcing this rule. Projects that favor minimal syntax can opt to disable allowParens
, whereas projects aiming for maximum clarity can enforce it, tailoring the stylistic guidelines to the team’s preferences without sacrificing code quality and understanding.
no-console
console
console
logging in production code since logging can potentially expose sensitive information to the console, which is deemed insecure especially in a production environment.console
statements, this rule can encourage developers to adopt or implement more sophisticated and configurable logging mechanisms that are suitable for both development and production environments, thus promoting better logging practices.console.warn
or console.error
) temporarily, without completely disregarding the utility of console methods for debugging purposes.no-const-assign
const
variablesconst
, directly upholding the language’s intended use of const
to declare constants which should not be reassigned after their initial definition. This helps maintain data integrity and predictability throughout the code.const
variable. By catching these attempts early, it aids in reducing potential debugging time and improves code reliability.const
) or mutable (let
).const
are not meant to be changed, improving comprehension and reducing the likelihood of accidental reassignments.no-constant-binary-expression
const isActive = true && getUserStatus();
can be simplified to const isActive = getUserStatus();
.true &&
operation reduces the amount of work the JavaScript engine needs to do to evaluate the expression.no-constant-condition
while (true)
creates an endless loop.if
statement with a constant condition might inadvertently hide code that is never executed or was intended to run under certain circumstances.no-constructor-return
throw
for invalid input values) instead of returning null or any other value, thereby promoting a more robust error handling strategy.
no-continue
continue
statementsno-continue
rule encourages writing more straightforward loop logic by disallowing continue
statements, making the flow of loops easier to understand at a glance. This helps in reducing the cognitive load when reading through loops, as the control flow is more predictable without jumps caused by continue
.
continue
, this rule can help prevent the accidental creation of infinite loops or loops that do not behave as intended. Especially in cases where continue
might skip necessary incrementation or evaluation at the end of a loop, rewriting the loop to avoid continue
can address such issues.
continue
might encourage the consolidation of conditions or the use of more efficient data structures or algorithms that could lead to faster execution times and lower memory usage.
no-control-regex
no-debugger
debugger
debugger
in code ensures that debugging code is not accidentally included in production builds, which can halt JavaScript execution in users’ browsers if the developer tools are open.debugger
statements, it serves as an educational tool for developers, especially those new to JavaScript, by highlighting practices that should be avoided and encouraging the development of debugging skills that do not rely on stopping the execution of code in a live environment.no-delete-var
null
or undefined
is a valid way to “empty” its value, contrasting with the delete
operator that does not work as some might intuitively think on variables.
delete
operator, which is aimed at removing properties from objects, not deleting variables declared with var
, let
, or const
. This distinction is crucial for developers to understand the limitations and proper uses of the delete
operator.
no-div-regex
/=
) can be confused for a division operation followed by an equal sign, especially in complex expressions./[=]/
), it highlights that the character is part of the regex pattern and not an operator.no-dupe-args
function
definitionsno-dupe-class-members
no-dupe-else-if
no-dupe-keys
no-duplicate-case
no-duplicate-imports
no-else-return
else
blocks after return
statements in if
statementsno-else-return
rule makes the code easier to read by eliminating unnecessary else
blocks after return
statements. This reduction in nesting can make the code flow more apparent, especially in functions with multiple conditional branches.
else
blocks when a return
statement precedes it, this rule encourages developers to write more straightforward and less complex code. This can lead to fewer logical errors, as there’s less cognitive load in understanding the control flow of the function.
else
blocks. This pattern can enhance the function’s clarity and maintainability.
else
statements, it also helps in avoiding potential scope leaks where variables declared in the else
block unintentionally shadow variables in the outer scope or vice versa. This leads to safer and more predictable code, especially in languages or runtime environments where block scoping is strictly enforced.
no-empty-character-class
no-empty-function
no-empty-pattern
allowObjectPatternsAsParameters
option, making it adaptable to different project guidelines or coding styles. This flexibility allows teams to apply stricter linting rules where necessary while accommodating certain patterns deemed acceptable in their specific context.
no-empty-static-block
no-empty
allowEmptyCatch
), thus providing flexibility where empty blocks might be intended or harmless. This caters to use cases where empty catch blocks are used for ignoring specific known errors that do not affect the flow of execution and do not require handling.
no-eq-null
null
comparisons without type-checking operators===
, !==
) for null
comparisons, helping developers avoid unintentional type coercion that could lead to bugs.==
, !=
) rules.null
, which can equate null
with undefined
, possibly leading to unintended logical branches in the code.no-eval
eval()
eval()
, which is a JavaScript function known for its potential security risks, as it allows for the execution of dynamically provided code that can come from an untrusted source. By disallowing eval()
, the rule helps to mitigate possible security vulnerabilities in the codebase.allowIndirect
), allowing for a degree of flexibility in application security practices. This is particularly useful in scenarios where indirect usage of eval()
might be considered safe or necessary, thereby providing teams the option to tailor the rule to their project’s specific requirements.eval()
but also sophisticated cases where eval
might be accessed indirectly through global objects or this
keyword, enhancing the coverage of security checks. This comprehensive approach ensures a more thorough vetting of the code against the use of eval, making it harder for security slips due to indirect usage to go unnoticed.eval()
might behave, such as its different implications in strict mode versus non-strict mode and its relation to the global scope. This sensitivity to the execution context ensures that the rule’s enforcement is nuanced and accurate, preventing both false positives and negatives in identifying unsafe eval
usage.no-ex-assign
catch
clausescatch
clause is not overwritten. Overwriting exception variables can lead to loss of original error information, making debugging harder.catch
blocks should remain immutable. This immutability makes the code more predictable and easier to reason about when diagnosing issues.no-extend-native
no-extra-bind
.bind()
.bind()
is used only when necessary, specifically when the function being bound actually uses this
. This can prevent developers from mistakenly believing that this
is being used inside a function when it is not, which could potentially save hours of debugging.
.bind()
calls, the codebase becomes cleaner and more performant because .bind()
creates a new function instance every time it is called, which is an unnecessary overhead when the bound function does not use this
.
this
) of functions in JavaScript. Understanding when and why to use .bind()
is crucial for writing effective JavaScript code, and adhering to this rule could serve as a learning tool for developers unfamiliar with function scopes and contexts.
.bind()
usage but also aids in maintaining clean code without manual intervention. The fix logic carefully checks that removing .bind()
will not introduce side effects, ensuring that automated code fixes do not break existing functionalities.
no-extra-boolean-cast
!!
or Boolean()
to convert a value to a boolean. These practices are unnecessary in contexts where JavaScript automatically coerces values to booleans, like in conditional statements.if
statements or while loops, hence promoting better understanding and cleaner use of the language’s features.no-extra-label
no-extra-parens
no-extra-parens
, is tailored to identify and rectify redundant parentheses, which not only streamlines the code but also enhances readability. Extra parentheses can mask the true intent of the code or create a false impression of complexity, leading to potential misinterpretations.no-extra-semi
no-fallthrough
case
statementsswitch
statements by ensuring that each case
is concluded properly before moving to the next one. By disallowing fallthrough (or enforcing explicit documentation of intentional fallthroughs), it prevents accidental execution of code under the wrong conditions, which can lead to hard-to-track bugs.
allowEmptyCase
, to accommodate different coding styles or project-specific guidelines. This makes it adaptable to various project needs without sacrificing the overall goal of preventing unintentional fallthrough.
no-floating-decimal
.5
is transformed into 0.5
, and 123.
is transformed into 123.0
.no-func-assign
function
declarationsno-global-assign
no-implicit-coercion
Boolean(someValue)
instead of !!someValue
makes the developer’s intention clear and improves code readability.+
for number conversion or !!
for boolean conversion might lead to unexpected results if the developer is not fully aware of the nuances of JavaScript coercion rules. Making these conversions explicit helps avoid such pitfalls.Number(value)
or String(value)
, it’s immediately clear what the developer intended, as opposed to trying to infer intent from the context around shorthand coercions.no-implicit-globals
no-implied-eval
eval()
-like methodseval()
-like methods which can be exploited for malicious purposes such as executing arbitrary code.eval()
-like methods, the rule encourages developers to adopt safer alternatives, such as using functions, which can lead to more secure code practices by reducing potential vectors for code injection attacks.eval()
but also other functions that can implicitly evaluate string expressions as code, such as setTimeout()
, setInterval()
, and execScript()
. This comprehensive approach ensures a wider range of potentially harmful code patterns are caught and flagged.no-import-assign
no-inline-comments
no-inner-declarations
function
declarations in nested blocksno-invalid-regexp
RegExp
constructorsu
and v
), thus aligning with ECMAScript specifications and ensuring broader compatibility and predictability of regex behavior across different JavaScript engines.no-invalid-this
this
in contexts where the value of this
is undefined
this
keyword in contexts where it might be undefined
, reducing the chances of runtime errors due to incorrect assumptions about the binding of this
.this
in various scopes, particularly in modular code where the global context does not automatically bind to this
, thereby keeping the code more consistent and predictable.capIsConstructor
, the rule offers flexibility in determining the validity of this
within constructor functions versus regular functions or methods, helping to align the rule’s behavior with the project’s coding standards or architectural decisions.this
is valid until it is first encountered within a function optimizes performance by avoiding unnecessary computations for functions that do not use this
, making the linting process more efficient without sacrificing thoroughness.no-irregular-whitespace
no-iterator
__iterator__
property__iterator__
property, which encourages developers to adhere to the standardized, well-supported iteration protocols like using Symbol.iterator
. This ensures code compatibility across different JavaScript environments and engines.
__iterator__
property, thereby improving the reliability of the code.
__iterator__
property, this rule implicitly promotes the use of ES6 features like the for…of loop or Symbol.iterator
method, which can lead to cleaner, more readable, and modern code patterns that are easier to understand and maintain.
no-label-var
no-labels
allowLoop
and allowSwitch
), it provides flexibility to enable labels for loops and switch statements when genuinely needed, catering to cases where labels might improve code clarity or control flow, without enforcing a blanket ban.no-lone-blocks
let
and const
declarations within unnecessary blocks, which might behave differently than the developer expects if misunderstood.no-lonely-if
if
statements as the only statement in else
blocksif
statements in else
blocks into else if
constructs, making the code easier to understand at a glance.if
statements in else
blocks, this rule promotes a coding style that can improve the overall quality of codebases by enforcing consistency in how conditional logic is written.no-loop-func
setTimeout
, mitigating issues related to closures capturing loop variables.
no-loss-of-precision
no-magic-numbers
0.1
directly in a calculation to defining it as DISCOUNT_RATE
. This improves code readability and maintainability by making the purpose of numbers clear.ignore
, enforceConst
, or ignoreArrayIndexes
, allowing teams to tailor the rule to their project’s needs and ensuring that exemptions like array indexes or default values are handled uniformly.no-misleading-character-class
u
flag. This ensures that developers do not unintentionally write regular expressions that fail to match intended characters.
u
flag to regular expressions containing characters that are represented by surrogate pairs or require multiple code points. This action directly helps to reduce debugging time and errors related to incorrect string matching.
u
flag in specific situations, this rule aids in maintaining consistency across the codebase regarding the treatment of Unicode characters in regular expressions. Consistent use of the u
flag can prevent subtle bugs that might occur in environments with differing default behaviors regarding Unicode handling.
no-mixed-operators
5 + 10 * 3 - 2
could confuse readers about the sequence of operations.(5 + (10 * 3)) - 2
.no-mixed-requires
require
calls to be mixed with regular variable declarationsrequire
calls with regular variable declarations. This can significantly enhance readability and maintainability, as it separates the inclusion of external modules from the declaration of variables derived from expressions or literals.
grouping
and allowCall
, the rule is flexible and can be adjusted to fit various coding conventions or project requirements. The grouping
option ensures that require
calls are either all bunched together or separately declares, making it easier to identify dependencies at a glance. The allowCall
option accommodates the practice of immediately invoking a required module, catering to patterns where this might be necessary or preferred.
require
, it encourages thoughtful structuring of module imports compared to dynamic or inline requirements that could lead to less predictable code behavior or harder-to-track dependencies.
require
calls—core, file, module, computed—thereby not only enforcing a clean coding practice but also paying attention to the nuances of module resolution in Node.js. This detailed approach helps developers think more carefully about the nature of their dependencies and could lead to more optimized and efficient code by encouraging the best use of Node.js modules.
no-mixed-spaces-and-tabs
no-multi-assign
let a = b = c = 5;
can be misleading about the intention behind the assignment operation and the scope of variables being affected.let c = 5; let b = c; let a = b;
) makes the code more readable and straightforward, thereby reducing the risk of unintentional errors.no-multi-spaces
no-multi-str
no-multiple-empty-lines
no-native-reassign
window
or undefined
, which could lead to severe implications for the application’s functionality.no-negated-condition
no-negated-in-lhs
in
expressions!'property' in object
can be mistakenly interpreted as checking if a negated string is a property in the object, rather than the intended functionality of checking if the property does not exist.
!('property' in object)
makes it immediately clear that the condition is evaluating the existence of ‘property’ in the object, and then negating that result, which aligns better with the developer’s intent.
in
operator. This reduces the likelihood of mistakes that could arise from developers using different patterns for similar checks.
in
operator has higher precedence than the !
operator, so !'property' in object
will be evaluated in an unexpected way (evaluating 'property' in object
first, then negating the result of the expression), leading to runtime errors or incorrect program logic. Ensuring the correct use of parentheses as enforced by this rule mitigates such risks.
no-nested-ternary
no-new-func
new
operators with the Function
objectFunction
constructor with new
operators, which is a practice that can lead to security issues such as injection attacks because it allows for the execution of dynamically generated code.new
and other function declaration styles, leading to more maintainable and readable code.Function
constructor is used, it aids in the code review process, reducing the time needed for manual code audits focused on spotting potentially unsafe JavaScript practices, thereby improving overall development efficiency.no-new-native-nonconstructor
new
operators with global non-constructor functionsnew
operator, which can lead to unexpected behaviors and bugs in the code. For example, using new String("Hello, world!")
creates an object instead of a primitive string.new
operator with non-constructor functions, this rule helps optimize the runtime performance of JavaScript applications. Objects created through the misapplication of new
with functions like String
or Number
can have a larger memory footprint and worse performance compared to their primitive counterparts.new String()
does not return a primitive string can be non-intuitive, especially for developers less familiar with JavaScript’s nuances.no-new-object
Object
constructors{}
) over the new Object()
constructor to create new objects, which promotes consistency in object creation and aligns with modern JavaScript best practices. It makes the code more readable and concise.Object
if the code is executed in a context where Object
might not refer to the native JavaScript Object constructor due to shadowing or redefinition, thus safeguarding against potential bugs.{}
is faster than invoking a constructor function like new Object()
, due to less overhead in the object creation process.no-new-require
new
operators with calls to require
new
operator with require calls, which is an uncommon or mistaken pattern in Node.js development. By disallowing this pattern, the rule helps maintain conventional use of require
for module importing, which is crucial for compatibility and understandability in Node.js applications.
new
with require
could potentially lead to incorrect initializations or unexpected behaviors in modules, as most modules exported with module.exports
are not designed to be instantiated with new
. This contributes directly to the reliability and stability of the application.
new
might lead to inefficiencies, especially if the module exports a singleton or a set of stateless utility functions. Removing unnecessary new
operators could lead to slight improvements in runtime performance by avoiding unnecessary constructor calls.
require
without new
), the code becomes more accessible to new developers or contributors. This consistency eases the understanding of how modules are imported and used throughout the application, making the codebase easier to navigate and maintain.
no-new-symbol
new
operators with the Symbol
objectSymbol
as a primitive value that cannot be constructed using new
. This rule enforces the standard, ensuring that symbols are created as the specification dictates, thus preventing runtime errors.
new Symbol
will throw a TypeError at runtime because Symbol
is not a constructor. By disallowing the new
operator with Symbol
, this rule helps avoid such errors, contributing to more robust and error-free code.
Symbol
in JavaScript, encountering this rule can serve as an educational point. It highlights the correct usage of Symbol
, distinguishing it from other objects and primitives in JavaScript, thereby reinforcing best practices.
Symbol()
without the new
operator, this rule ensures a consistent approach across the codebase. Consistency in coding practices not only makes the code easier to read and maintain but also aids in the onboarding of new developers, who can quickly learn the correct way to use symbols.
no-new-wrappers
new
operators with the String
, Number
, and Boolean
objects"Hello"
, 123
, false
) instead of their object counterparts (new String("Hello")
, new Number(123)
, new Boolean(false)
), which is a best practice for optimizing memory usage. Primitive values use less memory than their object equivalents because they are not objects and do not have the overhead associated with objects.new
operator with String
, Number
, and Boolean
, the rule indirectly encourages the use of literals, which are easier to read and write. Code readability is improved as literals are the conventional way to represent these values in JavaScript.new
operator can help avoid unexpected behavior in equality checks. Since new String("Hello")
creates an object, it will not be strictly equal (===
) to the primitive form "Hello"
, potentially leading to bugs that are hard to trace. This rule helps maintain the predictability of equality comparisons.no-new
new
operators outside of assignments or comparisonsnew
operator that are not used, reducing unnecessary memory usage and improving performance. By ensuring that new objects are assigned to a variable or used in a comparison, it ensures that every created object serves a purpose.new
but are never utilized, which can be a sign of incomplete implementation or a misunderstanding of how the objects should be used.new
operator. This can lead to more thoughtful code design and architecture, where objects are only created when they have a defined role, reducing the chance of side effects or memory leaks.no-nonoctal-decimal-escape
\8
and \9
escape sequences in string literals\8
and \9
escape sequences in string literals, addressing a niche but potentially confusing part of JavaScript syntax where these particular escapes do not represent valid escape characters and might lead to unintended behavior or interpretation in code.\8
and \9
into their respective Unicode escapes or simply suggesting the removal of the backslash to avoid creating unintended escape sequences.\8
and \9
escapes which do not have a clear or defined behavior in JavaScript.\8
or \9
follows a NULL escape (\0
), this rule thoughtfully handles edge cases where a simple replacement could inadvertently change the meaning of the literal (e.g., recommending the transformation into a Unicode escape to preserve the intended value without introducing legacy octal escapes). This nuanced approach helps to avoid inadvertently introducing errors while attempting to make the code compliant.no-obj-calls
Math
and JSON
are incorrectly treated as callable functions. By disallowing the calling of these global object properties as functions, the rule prevents TypeErrors that arise from such incorrect calls.
Math.round(5.76)
) and incorrect (Math(5.76)
) usage guides developers to follow best practices in the use of built-in JavaScript objects.
no-object-constructor
Object
constructor without an argument{}
for creating empty objects instead of new Object()
, which aligns with modern JavaScript best practices and can make the code easier to read and understand.{}
) can be more optimized by JavaScript engines compared to using the Object
constructor without arguments. This can contribute to minor improvements in the execution time of scripts, especially in environments where performance is critical.Object
constructor without arguments. For instance, in cases where the global Object
could have been shadowed or overwritten, leading to unexpected behavior. Enforcing the use of object literals removes the reliance on the global Object
constructor, thereby reducing the risk of such issues.no-octal-escape
no-octal
071
), it might be interpreted as an octal number rather than a decimal, affecting the program’s logic unexpectedly.no-param-reassign
function
parametersno-path-concat
__dirname
and __filename
path.join()
or path.resolve()
over direct string concatenation when combining __dirname
or __filename
with another string. This is crucial as it ensures that file paths are constructed in a manner that is cross-platform compatible, avoiding common pitfalls related to file path delimiters across different operating systems.\
) whereas Unix-based systems (like Linux and macOS) use a forward slash (/
). Direct string concatenation does not account for these differences, potentially leading to unresolved path errors when moving code between environments.path
module, which is designed to handle filesystem paths in a secure and consistent way. This can help in preventing security issues related to path manipulation, such as directory traversal attacks, by ensuring the use of well-tested methods provided by Node.js for constructing paths.__dirname
and __filename
, this rule also promotes code readability and maintainability. Using path.join
or path.resolve
makes the intention behind path construction clearer to anyone reading the code, as opposed to deciphering the purpose behind string concatenation operations. This clarity can be particularly beneficial in larger projects where understanding the construction of file paths quickly can save time and reduce confusion.no-plusplus
++
and --
++
, --
, and += 1
or -=
operators, which can lead to more readable and maintainable code.++
and --
are traditionally accepted, while still enforcing the rule elsewhere.++
and --
, it helps in avoiding unintended type coercion or tricky bugs that might arise when these operators are used in complex expressions or statements without clear intent.no-process-env
process.env
no-process-env
specifically targets the direct use of process.env
, ensuring that developers handle environment variables through a more secure and centralized manner (e.g., using frameworks like dotenv). This approach minimizes the risk of inadvertently exposing sensitive data.
process.env
, this rule advocates for a cleaner code base where environment variables are managed in a single location. This practice allows for easier updates and maintenance, especially when the application needs to scale or if there are changes in the environment variables.
process.env
. It acts as an automatic review mechanism that can catch potential issues during development or code review phases, long before the code is deployed, thus enhancing the overall security posture of the application.
no-process-exit
process.exit()
process.exit()
, which could lead to a poor user experience by not fulfilling the request properly or providing helpful feedback.process.exit()
would ungracefully shut down the entire process, affecting all ongoing and future requests.no-promise-executor-return
allowVoid
option), this rule enforces a promise usage pattern that aligns with best practices. This ensures that developers explicitly signal their intent when a return is not meant to pass a value along, making the code more readable and intention-revealing.
void
to ignore expressions or wrapping returns in braces, which not only helps in adhering to the best practices but also assists in faster code refactoring and reduces the manual effort required by developers to fix reported issues.
allowVoid
setting), which makes it adaptable to different coding styles and preferences. This specificity ensures that the rule can be effectively used across diverse codebases without causing unnecessary friction or false positives.
no-proto
__proto__
property__proto__
property, which is a de facto standard, but not part of ECMAScript’s specification until ES2015, and then only for browser compatibility.Object.create
, a more robust and standard approach to setting an object’s prototype, promoting code consistency and adherence to modern JavaScript standards.__proto__
, this rule helps to prevent potential prototype pollution vulnerabilities where an attacker could manipulate the prototype of a base object, affecting all objects that inherit from it and potentially leading to security issues.no-proto
rule also contributes to improving code performance and optimization. Accessing or modifying an object’s prototype chain via __proto__
is generally slower than other means, and some JavaScript engines might not optimize code containing __proto__
, leading to potential performance bottlenecks.no-prototype-builtins
Object.prototype
methods directly on objectsObject.prototype
methods directly on objects that might have their own properties or methods with the same names, avoiding unexpected behavior or shadowing issues.hasOwnProperty
are called in a context where their original functionality is guaranteed, particularly important in codebases dealing with objects with dynamically assigned or unknown properties.Object.prototype
directly, promoting best practices across the codebase and facilitating code readability and maintenance.Object.prototype
(e.g., objects created with Object.create(null)
), thus ensuring that the checks for properties are always conducted in a reliable and error-free manner.no-redeclare
no-redeclare
rule helps in avoiding confusion and potential errors by disallowing the redeclaration of variables within the same scope, which is crucial for maintaining clean, readable, and error-free code. For instance, redeclaring a variable sum
inside a loop, as shown in the “bad” example, could lead to incorrect calculations and hard-to-debug errors.
no-regex-spaces
no-restricted-exports
no-restricted-globals
no-restricted-imports
import
no-restricted-modules
require
no-restricted-properties
Math.pow
, by replacing them with modern equivalents like the **
operator for exponentiation. This ensures that the codebase remains up to date with the latest JavaScript features and best practices.no-restricted-syntax
for...of
instead of for...in
for arrays to avoid unintended property enumeration.
.map()
, .forEach()
, etc., instead of various loop constructs for array operations.
no-return-assign
return
statementsreturn
statements, which promotes clearer and more intentional code. By disallowing assignments in returns, it ensures that the return value is explicitly intended for output rather than performing an operation and returning the result in a single statement, which can be confusing.
=
) and equality operators (==
and ===
) can lead to errors that are hard to debug.
no-return-await
return await
return await
in an async function is redundant because the await
keyword is unnecessary when returning a promise in an async function. The JavaScript engine automatically awaits the promise before returning it to the caller.
await
might not always have a tangible performance impact, in certain cases, especially in hot code paths, removing unnecessary awaits could lead to slight performance improvements by reducing the overhead of additional promise resolutions.
await
usage, this rule encourages developers to have a better understanding of how asynchronous operations work in JavaScript, particularly how promises are returned and handled in async functions. This aligns with best practices for asynchronous code and helps prevent misunderstandings that could lead to bugs.
await
keywords, thus speeding up the development process and ensuring code style consistency across the codebase.
no-script-url
javascript:
urlsno-self-assign
=
) but also with compound assignment operators like &&=
, ||=
, and ??=
, it educates developers about the proper usage of these operators and promotes coding best practices.
no-self-compare
no-sequences
no-sequences
rule specifically targets the misuse of the comma operator, which can lead to unclear or unintended code behavior. By disallowing comma operators, developers are encouraged to write more explicit and straightforward code, thereby reducing the possibility of bugs caused by misunderstood sequence expressions.no-setter-return
FunctionDeclaration
, FunctionExpression
, and ArrowFunctionExpression
) ensures that the rule is comprehensive and applicable in a wide range of coding styles and scenarios. This broad coverage helps in effectively catching and addressing the issue of setter returns across different contexts and coding patterns, making it a versatile tool for codebase linting and enforcement of best practices.no-shadow-restricted-names
undefined
, NaN
, Infinity
, arguments
, and eval
within a local scope. For instance, redefining undefined
could lead to unpredictable behavior and bugs that are hard to track down.
arguments
object or the eval
function will work as expected without being inadvertently affected by local redefinitions.
arguments
or NaN
, which could be unclear and misleading, developers are prompted to use names that accurately reflect the purpose or content of the variable, enhancing code clarity and maintainability.
no-shadow
no-spaced-func
no-sparse-arrays
[1, , , , 5];
. This structure can lead to unintended bugs and inconsistencies in how the array’s elements are accessed and manipulated, as it might not be immediately clear to developers reading the code that the empty slots are intentional and not a mistake.
undefined
) for empty slots, as shown in the fix example, the rule enforces a more consistent and predictable array structure. This consistency aids in the readability of the code, as other developers (or even the original author returning to the code at a later date) will not have to guess the intent behind the array’s structure.
map()
and forEach()
, which will skip over empty slots in sparse arrays.
context.report
to highlight instances of sparse arrays in the code, assists developers in quickly identifying code that does not comply with this best practice. This immediate feedback loop can help educate developers on the potential issues with sparse arrays and encourage them to adopt more reliable coding patterns, improving the overall codebase’s robustness.
no-sync
allowAtRootLevel
) that can be configured to either permit or disallow synchronous methods at the root level, offering flexibility. This option allows for exceptions where synchronous methods might be necessary or harmless, such as in initial setup scripts, whilst still maintaining overall code quality and consistency.
no-tabs
allowIndentationTabs
) to allow tabs for indentation while still disallowing their use elsewhere. This flexibility means that teams who prefer tabs for indentation due to their adjustable width in editors can still adhere to the rule by disallowing tabs for alignment purposes, thus maintaining the primary goal of consistency across the team’s codebase.no-template-curly-in-string
${variable}
inside quotes, expecting the variable to be substituted, but since it’s not a template literal, it wouldn’t work as intended.
${}
inside regular strings is likely a mistake (a developer intending interpolation but using the wrong string delimiters), catching these errors early saves time and avoids potential runtime issues where the string doesn’t contain the expected dynamic content.
no-ternary
no-this-before-super
this
/super
before calling super()
in constructorssuper()
is called before this
is accessed, which aligns with JavaScript’s requirement for derived classes to initialize the parent class before using this
. This prevents runtime errors that occur when this
or super
is used before super()
is called, enhancing code reliability and correctness.super()
is always called first in derived class constructors, developers can quickly identify the class hierarchy and initialization order, which is crucial for debugging and maintaining the code.this
or super
before calling super()
, developers are reminded of the specific language rules related to class inheritance and constructor chaining, promoting best practices in object-oriented JavaScript programming.no-throw-literal
Error
or its subclasses, which is a best practice for error handling. This allows for consistent error handling mechanisms and makes it easier to debug and manage errors since they have a standard structure.Error
objects with meaningful messages. This practice enhances code readability and maintainability, as it provides clearer insight into the nature of the error.Error
objects for more complex error handling scenarios, such as throwing custom errors with additional properties (e.g., error codes). This promotes a more structured and scalable approach to error management across larger codebases.no-trailing-spaces
no-undef-init
undefined
undefined
by default if they are not initialized to any value, explicitly setting them to undefined
is unnecessary and can be safely removed without altering the behavior of the code.
undefined
makes the code simpler and more straightforward for other developers to understand, focusing their attention on initializations that do have meaningful values or side effects.
undefined
value for uninitialized variables. This can help new JavaScript developers learn and adhere to idiomatic JavaScript practices by seeing examples of clean, idiomatic code in the codebase.
no-undef
/*global */
comments/*global */
comments, this rule provides a flexible mechanism for developers to consciously decide to use global variables when necessary, promoting explicit documentation and understanding of dependencies on global scope.
typeof
operator provides fine-grained control to prevent false positives in situations where checking the type of an undeclared variable is intentional, thus maintaining the rule’s effectiveness without hindering certain coding practices.
no-undefined
undefined
as an identifierundefined
as an identifier, this rule helps maintain clarity and prevents ambiguity in codebases, ensuring that undefined
remains a predictable, non-overridden value in JavaScript. This is particularly useful in debugging sessions where the unexpected use of undefined
can lead to confusion.undefined
value by declaring variables or functions with the same name, which can lead to hard-to-track bugs and erratic behavior in the application since the value of undefined
is expected to be constant and unchangeable throughout the execution of the program.undefined
keyword.undefined
is handled and referred to in the codebase. By programmatically enforcing such standards, it helps new developers avoid adopting bad habits and aligns existing code with best practices through automated linting and potential fixes.no-underscore-dangle
allowAfterThis
, allowFunctionParams
), thereby accommodating use cases where underscore prefixes or suffixes may be a convention or requirement, such as in certain libraries or frameworks.enforceInMethodNames
and enforceInClassFields
, it gives teams the ability to enforce naming conventions more strictly in specific areas of the code, such as within class or method names, thereby tailoring the rule to align with specific coding standards or style guides.no-unexpected-multiline
no-unmodified-loop-condition
attempts
is not modified inside the loop, which could potentially lead to an infinite loop if checkInput
never returns true
.
no-unneeded-ternary
age >= 18 ? true : false
with a simpler age >= 18
.foo ? true : false
into just foo
or !!foo
depending on whether foo
is guaranteed to be a boolean expression, making the intention clearer and the code shorter.id ? id : expression
) into a logical OR operation (id || expression
). This encourages using logical operations over ternary for default assignments, which is generally more concise and idiomatic in JavaScript.no-unreachable-loop
no-unreachable
return
, throw
, continue
, and break
statementsreturn
, throw
, continue
, and break
statements, ensuring that the written code is efficient and does not include segments that will never be executed. This can prevent potential confusion when reading the code, as unreachable statements might misleadingly suggest they have an effect when they do not.
no-unsafe-finally
finally
blocksreturn
, throw
, break
, and continue
in finally
blocks can lead to unpredictable behavior and override the error handling or response from the try
or catch
blocks. This rule helps maintain the intended flow of execution, ensuring that any cleanup in the finally
block doesn’t inadvertently change the outcome of the try-catch-finally
structure.
finally
blocks, the rule encourages developers to write clearer and more maintainable code. The absence of such statements in finally
blocks prevents confusion about the flow of control and makes the code easier to follow, especially for developers who are new to the codebase or less familiar with such patterns.
finally
blocks can lead to unintended consequences, such as suppressing exceptions thrown in try
or catch
blocks or causing a function to return a different value than expected. By enforcing this rule, developers are prevented from introducing logic that could lead to hard-to-find bugs or unexpected behavior in production.
finally
blocks: The primary purpose of a finally
block is to execute cleanup code or release resources regardless of whether an exception was thrown, not to alter the program’s control flow. By disallowing control flow alterations within finally
blocks, this rule promotes the correct use of finally
blocks for their intended purpose, ensuring that they are used to safely and reliably clean up after a try-catch
block without interfering with the function’s outcome.
no-unsafe-negation
in
, instanceof
, <
, >
, <=
, >=
), leading to unexpected behaviors. For example, writing !key in object
, which JavaScript interprets as (!key) in object
, can lead to a significant bug because it checks if false
is in object
, not if key
is not in object
.
enforceForOrderingRelations
, it offers flexibility to teams to adopt stricter conventions for ordering relational operators (<
, >
, <=
, >=
). This adaptability ensures that teams can align the rule with their specific coding standards and practices, enhancing the consistency and predictability of negation logic throughout their codebases.
no-unsafe-optional-chaining
undefined
value is not allowedundefined
values which can lead to NaN errors. For instance, const result = obj?.b + 5;
might result in undefined + 5
without this rule.
undefined
values when using optional chaining, which can otherwise lead to unexpected behaviors or bugs.
??
) over logical OR (||
) with optional chaining to explicitly handle undefined
and null
values, ensuring that fallback values are used only in the intended cases.
undefined
in logical operations, conditional expressions, and other contexts where it might not be an acceptable value, by requiring developers to address these cases directly in the code.
no-unused-expressions
allowShortCircuit
, allowTernary
, and allowTaggedTemplates
, this rule offers flexibility, allowing teams to tailor the rule to fit their specific project needs or coding style guidelines without sacrificing the overall objectives of code clarity and efficiency.no-unused-labels
no-unused-private-class-members
no-unused-vars
no-use-before-define
no-useless-backreference
^(a)\1$
with ^(aa)$
, can lead to a direct improvement in the execution efficiency of regex operations. This refactoring guidance encourages the elimination of unnecessary complexity in regular expressions, contributing to cleaner and more decipherable code.no-useless-call
.call()
and .apply()
.call()
and .apply()
methods, which, when unnecessary, can lead to code that is harder to read and understand. By pushing developers towards direct function calls, it aims to enhance code readability and simplicity.
.call()
and .apply()
in contexts where a simple function call would suffice, this rule aids in optimizing performance. These method calls introduce additional overhead that is unnecessary when the function being called doesn’t require an altered this
context or an array of arguments to be spread.
.call()
and .apply()
are primarily used for controlling the execution context of a function or for passing arguments as an array, their misuse can introduce subtle bugs, especially in cases where the this
argument or the arguments list is incorrectly specified. This rule helps maintain the integrity of function calls by ensuring that these methods are only used when absolutely necessary.
.call()
and .apply()
, reinforcing best practices around function invocation and the JavaScript execution context. By highlighting unnecessary usages, it prompts developers to think critically about whether manipulating the this
binding or passing an array of arguments is truly needed, fostering better coding habits.
no-useless-catch
catch
clausesno-useless-computed-key
no-useless-concat
no-useless-constructor
no-useless-escape
no-useless-rename
no-useless-return
return;
statements at the end of functions simplifies the function’s logic.
no-var
let
or const
instead of var
let
or const
for variable declarations, which are block-scoped, as opposed to var
, which is function-scoped. This reduces the risk of variables being unintentionally accessed or modified in outside scopes, increasing code maintainability and reducing potential bugs.
const
instead of var
, this rule nudges developers toward declaring variables that are not intended to be reassigned as constants. This can contribute to more predictable code and embraces the immutability concept, which is a cornerstone of functional programming paradigms.
let
and const
have TDZ constraints, this rule helps in identifying potential reference errors caused by accessing a let
or const
variable before it’s declared, thereby eliminating hard-to-debug temporal errors.
var
to let
or const
(e.g., variables declared in a switch case, loop closures, redeclarations) underscore its role in preventing scope-related bugs. By avoiding modifications in these complex scenarios without manual review, the rule protects against introducing reference and scope errors that could break the existing logic, ensuring that automated code fixes do not inadvertently introduce new issues.
no-void
void
operatorsvoid
operator. By preventing void
from being used to explicitly ignore a promise or an expression’s result, it encourages developers to handle these outcomes properly, potentially reducing the number of uncaught errors or unhandled promise rejections in the codebase.void
to disregard a function’s return value or a promise, developers are encouraged to either directly handle the function’s outcomes or consciously choose to not assign or react to them, making the code intentions clearer and more maintainable.void
for controlling the execution flow in asynchronous operations. This can lead to better-designed code, where asynchronous functions are awaited or their promises are properly chained, leading to more predictable and debuggable code behavior.allowAsStatement
option within the rule allows teams to enforce this rule while still permitting void
as a statement in cases where it might be considered acceptable or necessary. This balanced approach ensures that developers can follow best practices without completely losing the flexibility to use void
in a restricted, perhaps more controlled manner.no-warning-comments
no-whitespace-before-property
object .property
or array [index]
into object.property
or array[index]
, which is the standard notation.
5 .toString()
), ensuring the integrity of the code’s execution.
no-with
with
statementswith
statements, which can make it harder to determine where variables are coming from, especially in larger code bases.with
statements, this rule encourages more explicit reference to object properties, leading to clearer and more predictable code behavior, reducing the chance of referencing a wrong property due to scope confusion.with
statements, which can lead to mistaken assumptions about the existence or value of variables.with
statements are not allowed in strict mode in ECMAScript 5 and later, enforcing this rule helps ensure compatibility with strict mode, thereby future-proofing the code and taking advantage of strict mode’s benefits, such as catching some common coding bloopers and preventing, or throwing errors, when relatively “unsafe” actions are taken.nonblock-statement-body-position
if
, while
, for
, etc.), which can significantly improve code readability and maintenance by ensuring that the code follows a uniform layout pattern. When the positioning of single-line statements is consistent across a codebase, it becomes easier for developers to read and understand the logic at a glance without needing to adjust to different style preferences.
if
, while
, do
, for
, for...in
, for...of
), ensuring comprehensive enforcement of statement body positions across a wide array of control flow statements. This extensive coverage makes the rule highly versatile and ensures that most, if not all, instances of single-line control flow statements in a codebase are validated and corrected if necessary, leading to a more consistent and cleaner codebase overall.
object-curly-newline
object-curly-spacing
object-property-newline
object-shorthand
one-var-declaration-per-line
one-var
always
, never
, or consecutive
. This feature can save developers time during refactoring and help new team members adhere to project standards without manually adjusting each declaration.require
statements differently, the rule offers flexibility. This caters to various coding styles and practices, enabling teams to enforce declaration styles that best suit their project’s needs while considering the nature of variable usage.operator-assignment
+=
, *=
, %=
, etc.) which can make the code more concise and easier to read, especially in simple arithmetic operations. By transforming expressions like x = x + 1
to x += 1
, it eliminates redundancy and makes the intention of the code clearer at a glance.
a = b * a
being different from a *= b
in certain contexts).
operator-linebreak
padded-blocks
padding-line-between-statements
prefer-arrow-callback
function
expressions are used unnecessarily.this
context of the enclosing scope, which mitigates common pitfalls associated with this
in callback functions, especially for beginners not familiar with function binding or the behavior of this
in JavaScript.this
binding is necessary and cannot be achieved through arrow functions, providing flexibility in enforcing this rule to accommodate different coding styles and requirements.prefer-const
const
declarations for variables that are never reassigned after declaredconst
over let
for variables that are not reassigned, which leads to safer coding patterns by preventing unintentional variable reassignments that can introduce bugs into the code. This ensures that when a variable is declared and not meant to change, its immutability is enforced, making the code more predictable.const
for variables that are initialized once and not reassigned. This can lead to cleaner and more effective use of ES6 features, improving the overall quality of JavaScript code.prefer-destructuring
prefer-exponentiation-operator
Math.pow
in favor of the **
operator**
exponentiation operator over the verbose Math.pow
function, aligning with contemporary JavaScript practices for readability and succinctness.Math.pow
, as native operators like **
are often better optimized by JavaScript engines than equivalent method calls.Math.pow
calls to the **
operator, considering edge cases like the presence of comments or the necessity to parenthesize operands to preserve the original expression’s intent, ensuring a correct and risk-free code transformation.prefer-named-capture-group
prefer-numeric-literals
parseInt()
and Number.parseInt()
in favor of binary, octal, and hexadecimal literalsparseInt()
or Number.parseInt()
when converting strings representing numbers in these bases into numbers. This practice can improve code readability and make the developer’s intention clearer, as literals visually distinguish the base of the number at first glance.
parseInt()
with the equivalent numeric literal, if and only if it’s guaranteed not to change the behavior of the code. This automated correction reduces the chance of manual errors during refactoring and speeds up the process of aligning existing code with this best practice.
parseInt()
in favor of literals for binary, octal, and hexadecimal numbers, this rule can help prevent errors that arise from forgetting to specify the radix (base) parameter in parseInt()
. Using literals eliminates the risk of the function defaulting to base 10, which can lead to subtle bugs that are hard to catch.
parseInt()
with a numeric literal will not result in invalid JavaScript code or change the parsed value, especially considering edge cases like strings with numeric separators or invalid binary, octal, or hexadecimal numbers. This cautious approach ensures that any automated code modification introduced by the rule’s fix option respects the original logic, avoiding potential runtime errors.
prefer-object-has-own
Object.prototype.hasOwnProperty.call()
and prefer use of Object.hasOwn()
Object.prototype.hasOwnProperty.call()
, which is an indirect way of determining if an object has a given property. This method includes a longer chain of property access and method call, which can be less clear and harder to read than the proposed alternative.
Object.hasOwn()
aligns with the evolution of JavaScript, embracing newer and more efficient methods introduced in recent ECMAScript versions. This ensures that the codebase remains modern and benefits from language improvements.
Object.hasOwn()
could potentially be more efficient than Object.prototype.hasOwnProperty.call()
due to the latter’s need to access the prototype chain explicitly and the additional function call overhead.
Object.hasOwn()
, the rule helps prevent common mistakes related to the this
binding in the hasOwnProperty
method call, and improves readability by using a static method directly on the Object
class, making the intention of the code more immediately clear to readers.
prefer-object-spread
{...obj}
) over Object.assign({}, obj)
, this rule encourages the adoption of ES6+ syntax, which is more concise and readable for merging objects.
Object.assign
when merging objects, as it’s more optimized for this specific use case.
Object.assign
, particularly when the first argument is an empty object literal. This can make code easier to read and maintain.
Object.assign
with object literals and other sources, there’s a potential risk of unintended side effects if accessor properties (getters/setters) are present in the sources. Object spread syntax doesn’t invoke getters or setters, thus preventing these side effects.
prefer-promise-reject-errors
prefer-reflect
Reflect
methods where applicableReflect
API for operations like apply
, call
, defineProperty
etc., which is designed to provide a more standardized and cleaner way to perform these operations as compared to their traditional counterparts in Object
and Function.prototype
. This can lead to more readable and maintainable code by using a unified approach.
Function.prototype.apply
and Object.defineProperty
. For example, Reflect.apply
and Reflect.defineProperty
are less error-prone and more predictable in handling edge cases, improving the robustness of the code.
Reflect.deleteProperty
vs delete
operator). This is particularly useful in scenarios involving proxied objects, where direct operations might inadvertently trigger traps.
Reflect
, through the rule’s support for exceptions. This flexibility allows for nuanced enforcement of the rule based on the project’s specific requirements or coding conventions, ensuring that the use of Reflect
is encouraged without being overly restrictive.
prefer-regex-literals
RegExp
constructor in favor of regular expression literalsRegExp
constructor to enhance code readability. Regular expression literals provide a clear and concise syntax for creating regular expressions, making the code easier to read and understand at a glance.RegExp
constructor calls and regex literals, leading to more uniform code.RegExp
constructor are static strings, thereby simplifying the syntax.prefer-rest-params
arguments
...args
is more explicit than the vague arguments
object, making the developer’s intention clearer.arguments
with rest parameters, it helps avoid the common pitfalls associated with the arguments
object, such as its non-Array nature. The arguments
object is array-like but lacks array methods, requiring additional steps (like conversion to an actual array) to use those methods, which rest parameters do not.arguments
object is used improperly. For example, passing arguments
directly to another function can lead to deoptimizations in some JavaScript engines because the engine can’t as easily optimize the passing of arguments
due to its dynamic nature. Rest parameters do not have this issue as they are treated as any other parameter.prefer-spread
.apply()
apply()
method. This ensures codebases stay up-to-date with the latest JavaScript features, improving readability and maintainability..apply()
, this rule helps to avoid indirect function invocation. This can lead to clearer, more direct code that is easier to understand, as the intentions behind spreading arguments or concatenating arrays become more explicit.this
context in .apply()
calls. Since the spread operator does not involve explicitly binding this
, it reduces the likelihood of errors related to incorrect this
bindings, making it safer to use.apply()
, which might be used in mutating methods, the spread operator in expressions like array concatenation does not mutate the original array, leading to code that is easier to reason about and debug.prefer-template
"Your full name is: " + firstName + " " + lastName + "."
into Your full name is: ${firstName} ${lastName}.
, which is easier to comprehend at a glance.
${}
and backticks), when converting string concatenations into template literals. This reduces the risk of introducing syntax errors or unintended behavior during the conversion process.
+
). This can lead to cleaner code, particularly when dealing with long strings or strings that require dynamic content.
quote-props
quotes
backticks
, double
, or single
quotes) throughout the codebase, reducing the cognitive load when reading and understanding code.radix
parseInt()
parseInt()
. Without explicitly stating this radix, numeric strings with leading zeroes could be interpreted differently across environments, leading to inconsistencies like “071” being processed as an octal value in some cases. This rule ensures developers include a radix, preventing such ambiguity.
require-atomic-updates
await
or yield
await
or yield
operations, which could result in incorrect values being read or written. This is especially relevant in the given context where assignments to variables that occur after an await
or yield
could lead to outdated values being used.await
expressions in temporary variables before using them in further calculations), the rule helps maintain the integrity of variable values throughout the execution flow.require-await
await
expressionawait
inside async functions, which ensures that the async functions leverage the asynchronous functionality they promise. This prevents developers from mistakenly defining functions as async without actually using await, which could lead to confusion about the nature and behavior of the function.
await
expression, the rule helps in identifying functions that are unnecessarily declared as asynchronous. This can lead to minor performance improvements since async functions come with a little overhead compared to non-async functions.
async
keyword explicitly indicates that an asynchronous operation is being performed within the function. It clarifies the developer’s intent to others reading the code, making it easier to understand the flow of asynchronous operations.
await
but forget to do so. This rule would catch such oversights, potentially saving time in debugging asynchronous logic issues.
require-jsdoc
FunctionDeclaration
nodes by default, promoting documentation of functions which enhances code readability and maintainability. It specifically targets situations where functions are declared, emphasizing the importance of documenting what a function does, its parameters, and its return value.MethodDefinition
, ClassDeclaration
, ArrowFunctionExpression
, and FunctionExpression
. This targeted approach means teams can tailor the rule to their project’s specific documentation needs, focusing on the parts of their codebase that they find most critical to document.FunctionDeclaration
types by default and allowing for configurable enforcement on other types, this rule encourages developers to adopt good documentation practices early in the development lifecycle. This can lead to a more understandable codebase for new team members or when revisiting older code, ultimately aiding in the ease of code maintenance and scalability.require-unicode-regexp
u
or v
flag on RegExpu
or v
flag, developers are made aware of and encouraged to consider these Unicode-specific behaviors.u
or v
flag, the rule implicitly requires developers to think about and understand how their regex patterns interact with Unicode characters, leading to higher quality code that is less prone to bugs related to character encoding.require-yield
yield
yield
keyword, promoting correctness in asynchronous or iterable operations.rest-spread-spacing
semi-spacing
requireSpaceBefore
and requireSpaceAfter
allows teams to adhere to their specific coding standards, whether that involves spaces before semicolons, after them, both, or neither. This level of customization ensures that the rule can be adapted to various coding styles and preferences.semi-style
semi
sort-imports
allowSeparatedGroups
. This feature allows for logical grouping of imports (e.g., third-party modules vs. local modules), making it easier to differentiate various types of imports and enhancing the organization of code.
sort-keys
sort-vars
space-before-blocks
arrow-spacing
, keyword-spacing
, switch-colon-spacing
). This thoughtful design prevents situations where enabling one rule might lead to violations reported by another, thus streamlining the linting process and reducing the need for developers to manually address rule overlap or discrepancies.
space-before-function-paren
function
definition opening parenthesisspace-in-parens
space-infix-ops
=
, +
, ?
, :
, which can significantly enhance the legibility of complex expressions and assignments by visually separating operands from their operators.int32Hint
for special cases like bitwise operations ending in |0
, it provides flexibility, allowing teams to tailor the rule to their specific needs or coding standards without compromising on the overall goal of improved code clarity and consistency.space-unary-ops
typeof
and delete
) and symbol-based unary operators (!
, ++
, etc.), it ensures that the code is easier to read and understand, especially for new developers or those reviewing code.
options
allowing teams to enforce spacing policies that best fit their style guide or personal preference. For example, a project can decide to have spaces after word operators but not after non-word operators, providing flexibility to adhere to various coding standards and preferences.
spaced-comment
//
or /*
in a comment//
or /*
), which improves the readability of comments within the code. By enforcing a space, the comments become easier to distinguish from the code that follows, aiding in quick scanning and understanding of code annotations.
strict
'use strict';
is unnecessary, such as in classes and modules where strict mode is implied, helping to clean up the codebase and improve readability.'use strict';
directives within the same scope prevents potential JavaScript errors and enforces a cleaner code structure, especially in larger and more complex codebases where manual tracking would be prohibitive.switch-colon-spacing
symbol-description
Symbol
is created with a descriptive string, which facilitates debugging by making it clear what each symbol is intended for. Without a description, symbols are harder to differentiate, especially in a debugging session where you’re inspecting values.template-curly-spacing
template-tag-spacing
fix
function can automatically adjust spacing to meet the rule’s requirements without developer intervention.unicode-bom
use-isnan
isNaN()
when checking for NaN
NaN
can be directly compared using equality or inequality operators. Since NaN
is the only value in JavaScript that is not equal to itself, direct comparisons like value === NaN
will always return false, leading to bugs in the code. By enforcing the usage of isNaN()
, it ensures that checks for NaN
are correctly performed.
NaN
, thinking it will match when the switch expression evaluates to NaN
. However, this will never work as intended because of how JavaScript treats NaN
. This rule helps avoid such ineffective code by flagging direct NaN
usage in switch cases and suggesting alternatives that correctly determine if the value is NaN
.
.indexOf()
or .lastIndexOf()
, developers might expect these methods to find NaN
in an array. However, due to the same equality comparison issue, these methods will not work as intended when directly passed NaN
as a parameter. This rule highlights these incorrect usages, directing developers towards more suitable methods for checking the presence of NaN
in arrays, such as using the isNaN()
function within a filtering method like array.some()
.
NaN
to use the isNaN()
function, this rule promotes clearer intent and more reliable code. Direct comparisons and method usages that don’t work with NaN
as expected can lead to hidden bugs and unintended code paths. This rule helps developers recognize and correct these patterns, leading to more predictable and debuggable code, especially for those who may be newer to JavaScript and unaware of the unique nature of NaN
.
valid-jsdoc
@returns
over @return
) helps maintain consistency across the codebase’s documentation. Consistent use of JSDoc tags can make the documentation easier to read and understand, and prevent confusion that might arise from the use of synonyms or varied tag names across different parts of the project.undefined
do not have a @return
or @returns
tag unless explicitly required. This minimizes unnecessary documentation and keeps the focus on documenting elements that provide value, enhancing the overall quality and relevance of the code documentation.valid-typeof
typeof
expressions against valid stringsvars-on-top
var
declarations be placed at the top of their containing scopevar
declarations at the top. This structure can make the code easier to read and understand, since variable declarations are not scattered throughout the function.
var
declarations to the top of their scope. Declaring them at the top aligns the source code with how the JavaScript engine interprets it, making the developer’s intention clear and avoiding unintended behavior.
wrap-iife
function
invocationscall
and apply
when checking for wrapping. This consideration ensures that even when IIFEs are invoked using these methods, they are also wrapped according to the specified style, extending the rule’s coverage and ensuring consistency even in these less common cases.
wrap-regex
/abc/.test("abcabc");
to (/abc/).test("abcabc");
, clearly delineating the regex literal from the method call, making the code easier to understand at a glance.
/abc/.test("abcabc");
could be misinterpreted by developers unfamiliar with the nuances of JavaScript’s syntax, wrapping the regex in parentheses removes ambiguity about the order of evaluation.
yield-star-spacing
*
in yield*
expressionsyield*
expressions, which enhances code readability and maintainability by having a uniform appearance.*
in yield*
expressions, by enforcing a standard spacing convention.*
in yield*
expressions, saving developers time and effort in manually correcting these to adhere to the preferred style.before
, after
, both
, neither
) to cater to different coding style preferences or project-specific guidelines, thus providing flexibility in enforcing the rule across various codebases.yoda
18 <= age
), which can be less intuitive to read compared to the traditional format (e.g., age >= 18
). This helps in maintaining a more natural reading order in conditional statements, enhancing code readability.