accessor-pairs
Enforce getter and setter pairs in objects and classes
Enforces a consistent coding pattern that improves code readability and maintainability by ensuring that if a getter is defined for a property, a corresponding setter should also be defined, and vice versa. This reduces confusion for future developers who might expect to modify a property that only has a getter defined.
Helps in preventing unintentional read-only or write-only properties in objects and classes unless explicitly intended by the developer. This can be crucial in data encapsulation practices where the control over how a property’s value is set or retrieved needs to be closely managed.
The rule’s configurability allows teams to enforce the presence of getter-setter pairs according to their specific project requirements, such as checking for getter without setter or setter without getter, or even enforcing these rules for class members. This flexibility supports adherence to various coding standards and best practices across different types of projects.
Supports better design patterns in JavaScript programming by encouraging the use of getters and setters for controlling property access, which is a fundamental aspect of object-oriented programming. This can lead to more robust and secure code, as it allows for validation logic or side effects to be executed when properties are accessed or modified.
array-bracket-newline
Enforce linebreaks after opening and before closing array brackets
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
Enforce consistent spacing inside array brackets
This ESLint rule enforces a consistent spacing pattern inside array brackets, which directly impacts code readability and styling uniformity. This can be particularly beneficial in collaborative projects where maintaining a consistent coding style across multiple developers is crucial for project maintainability.
The rule provides an option to configure the desired spacing pattern either to always have spacing within array brackets or never have it. This allows teams to adapt the rule based on their coding standards and preferences, ensuring that the enforcement aligns with the team’s agreed-upon style guide.
The rule includes exceptions for single elements, objects within arrays, and arrays within arrays, which adds flexibility. This nuanced approach allows teams to enforce spacing rules while accommodating specific cases where a different spacing might be more readable or logical, ensuring the rule can be adapted to various coding scenarios without being overly rigid.
It automatically fixes spacing inconsistencies by adding or removing spaces as needed. This auto-fix feature significantly reduces the time and effort required for developers to comply with the spacing rules, allowing them to focus more on logic and less on formatting, ultimately speeding up the development process.
array-callback-return
Enforce return
statements in callbacks of array methods
This ESLint rule ensures all callbacks of array methods like .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.
The rule’s flexibility with options such as 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.
The inclusion of suggestions for fixes (like wrapping non-returning arrow functions in braces or prepending 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.
By checking the reachability of the last code path segment, the rule intelligently detects functions where not all paths return a value, further ensuring the reliability and predictability of the code. This promotes best practices in writing clean, error-free JavaScript code, especially in complex functions with multiple code paths.
array-element-newline
Enforce line breaks after each array element
multiline
, minItems
), allowing teams or projects to tailor the rule to match their coding style guidelines, thus maintaining codebase uniformity.arrow-body-style
Require braces around arrow function bodies
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
Require parentheses around arrow function arguments
arrow-spacing
Enforce consistent spacing before and after the arrow in arrow functions
const add = (a,b)=>a+b;
to the more readable const add = (a, b) => a + b;
.block-scoped-var
Enforce the use of variables within the scope they are defined
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
Disallow or enforce spaces inside of blocks after opening block and before closing block
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
Enforce consistent brace style for blocks
callback-return
Require return
statements after callbacks
camelcase
Enforce camelcase naming convention
This rule enforces a unified naming convention which improves the readability and consistency across the codebase by ensuring that variables, functions, and other identifiers are named in camelCase. This makes it easier for developers to understand the purpose and use of different entities within the code.
It includes exceptions through its options, such as allowing certain patterns or names (via the 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.
The rule is designed to avoid redundant reporting, particularly in the context of destructuring and shorthand notation, by using a Set to track reported nodes. This ensures that developers are not overwhelmed with duplicate warnings for the same issue, making the linting feedback more actionable and focused.
It supports backward compatibility options that prevent reporting in certain legacy scenarios, such as when identifiers are used in call expressions or as default values in destructuring or parameters. This consideration helps teams gradually adopt camelCase naming conventions without having to refactor existing codebases extensively before they can benefit from this rule.
capitalized-comments
Enforce or disallow capitalization of the first letter of a comment
class-methods-use-this
Enforce that class methods utilize 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
Require or disallow trailing commas
Ensures Consistency Across Codebases: By applying a specific style to trailing commas, whether it’s enforcing their presence or absence, the rule helps maintain a consistent code style across different parts of the project or even across different projects within an organization.
Eases Git Diffs: When trailing commas are enforced, adding new elements to objects or arrays doesn’t require modifying the line above to add a comma. This results in cleaner Git diffs where only the new lines are added, making code reviews more straightforward and minimizing merge conflicts.
Simplifies Array and Object Modification: By requiring trailing commas in multiline arrays and objects, developers can more easily add, remove, or reorder elements without having to worry about comma management, reducing the likelihood of syntax errors in modifications.
Adapts to Coding Standards with Flexibility: The rule is configurable to cater to different coding preferences and standards—‘always’, ‘never’, ‘always-multiline’, and ‘only-multiline’. This flexibility allows teams to adopt the convention that best suits their workflow and the readability of their code, whether they prefer a more traditional approach or one that leverages the benefits of trailing commas in modern JavaScript environments.
comma-spacing
Enforce consistent spacing before and after commas
comma-style
Enforce consistent comma style
This rule, when enforced, ensures a uniform comma style across various structures such as arrays, objects, functions, and more. Using it helps in maintaining a consistent code appearance, which can make the code easier to read and prevent errors related to irregular comma placements.
By offering customizable options and handling exceptions, the rule provides flexibility, allowing teams or projects to cater to specific stylistic preferences or requirements. This adaptability is crucial for aligning the linting rules with the project’s coding standards.
The rule includes fixer functions that automatically adjust the comma style to meet the specified guideline. This automated correction saves developers time during coding or code review processes, as they don’t have to manually fix each comma placement.
By targeting specific node types and their properties or elements (e.g., VariableDeclaration, ObjectExpression, ArrayPattern), the rule ensures that the comma style is enforced in both simple and complex language constructs. This thoroughness aids in catching inconsistencies that might be overlooked during manual reviews.
complexity
Enforce a maximum cyclomatic complexity allowed in a program
computed-property-spacing
Enforce consistent spacing inside computed property brackets
The rule ‘computed-property-spacing’ enforces a consistent spacing style inside computed property brackets, which can significantly improve code readability and maintainability by ensuring that all computed properties follow a single, consistent format. This helps developers to quickly understand the code, especially in large codebases where consistency is crucial for navigating and understanding different parts of the application.
It provides options to configure the spacing requirement as ‘always’ or ‘never’, giving teams the flexibility to tailor the rule to their coding standards. This adaptability ensures that the rule can support different stylistic preferences, making it applicable to various projects with distinct code style guidelines without forcing a one-size-fits-all approach.
The rule includes automated fixers that can automatically adjust spacing within computed properties to comply with the configured style. This feature saves time during code review and development by reducing manual linting efforts and helps maintain focus on more complex logic and application development tasks, rather than formatting.
By supporting automatic enforcement for class members when the ‘enforceForClassMembers’ option is enabled, it extends its utility beyond object properties to class member access expressions. This ensures that modern JavaScript classes and object-oriented approaches benefit from the same level of consistency and readability as traditional object notation, keeping the codebase modern and coherent.
consistent-return
Require return
statements to either always or never specify values
treatUndefinedAsUnspecified
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
Enforce consistent naming when capturing the current execution context
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
Require super()
calls in constructors
Enforces a key aspect of class inheritance in ES6 by requiring that super()
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.
This rule aids in detecting unreachable code segments where 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.
Helps maintain consistency and readability in codebases that utilize ES6 class syntax by enforcing a common pattern for constructor definitions in derived classes. This uniformity makes the code easier to read and understand, especially for developers who are new to a project.
By explicitly checking and reporting the use or omission of 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
Enforce consistent brace style for all control statements
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
Enforce default clauses in switch statements to be 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
Require default
cases in switch
statements
switch
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
Enforce default parameters to be last
The rule 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.
By enforcing default parameters to be at the end, it prevents potential errors when calling functions without specifying all arguments. Since JavaScript functions allow calling with fewer arguments than declared, having default parameters at the end ensures that the omitted arguments correctly map to those defaults, reducing the likelihood of unintended outcomes.
This rule aids in improving code readability and clarity. When a function with default parameters is called, it’s much clearer which arguments are optional and what their default values are. This clarity is especially beneficial for new team members or when revisiting old code, as it provides immediate context on how the function can be used without needing to refer back to its definition.
Implementing the 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
Enforce consistent newlines before and after dots
dot-notation
Enforce dot notation whenever possible
Improves readability: The enforcement of dot notation for property access enhances the readability of the code. It is generally easier and more straightforward to understand 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.
Encourages best practices: Dot notation is widely regarded as a best practice in JavaScript for accessing known and predictable property names. This rule aligns with such best practices, promoting code that is in harmony with common JavaScript idioms and patterns, thereby making it easier for developers to maintain and understand the code.
Automates code maintenance: Through its fix method, this rule offers automated code refactoring by replacing bracket notation with dot notation where applicable. This automation saves developer time and reduces the likelihood of manual errors during refactoring. It ensures that the codebase remains clean without requiring extensive effort from developers to adhere to this style guideline.
Configurability for exceptions: The rule provides options to allow for exceptions, such as when working with reserved keywords or when a certain pattern for property names is allowed that cannot be accessed with dot notation. This flexibility ensures that while the rule enforces a general best practice, it remains adaptable to specific coding requirements or styles, making it suitable for a wide range of projects without forcing unnecessary code changes.
eol-last
Require or disallow newline at the end of files
eqeqeq
Require the use of ===
and !==
This rule ensures that the code adheres to strict equality checks (===
and !==
), preventing unintended type coercion that can occur with abstract equality checks (==
and !=
). This enhances code reliability and predictability in comparisons.
By allowing configuration options such as “always”, “smart”, or considering 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.
The rule includes automatic fixing for cases where it’s safe to convert abstract equality into strict equality, specifically when comparing literals of the same type or in typeof
comparisons. This feature assists developers by reducing manual refactoring effort and accelerating the process of adopting strict equality checks.
Includes a specific check for 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
Enforce “for” loop update clause moving the counter in the right direction
This rule helps prevent infinite loops by ensuring that the counter in a “for” loop is moving in a direction that eventually meets the loop’s exit condition. For example, a counter that mistakenly decreases (i--
) when it should increase to reach a termination condition (i < 10
) could cause a loop to never terminate.
It specifically addresses and catches the misuse of update expressions (++
, --
) 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.
By checking if the update clause of the “for” loop correctly corresponds with the loop’s termination condition, this rule can help catch logical errors early in the development process. This contributes to more robust, error-free code by highlighting potential problems that are not always immediately evident through manual code reviews or testing.
It aids in maintaining code readability and understandability by enforcing a standard direction for counter updates in “for” loops. When the counter moves in the expected direction in relation to the loop’s completion condition, it aligns with most developers’ expectations and understanding of how “for” loops should operate, making the code easier to read and reason about.
func-call-spacing
Require or disallow spacing between function identifiers and their invocations
func-name-matching
Require function names to match the name of the variable or property to which they are assigned
Enforcing the use of this ESLint rule improves code readability and maintainability by ensuring that function names directly reflect their assignments. This makes it easier for developers to understand what a function does at a glance, particularly when navigating large codebases.
The rule aids in reducing developer confusion by preventing situations where a function’s name suggests a different functionality or scope than its actual implementation. By enforcing name matching, it becomes evident what role a function plays without needing to delve into its definition.
By including options to consider property descriptor patterns and CommonJS module exports, this rule is versatile enough to enforce consistent naming conventions across various coding paradigms and project structures. This adaptability makes it valuable for projects that incorporate multiple patterns for function declaration and exports.
The rule mitigates the risk of errors stemming from refactorings where a function’s name might change without updating its references or assignments, potentially leading to discrepancies that are difficult to debug. Enforcing matching names helps ensure that such updates are more atomic and self-contained, reducing the likelihood of introducing bugs during the refactoring process.
func-names
Require or disallow named function
expressions
This ESLint rule helps enforce a consistent naming convention for function expressions, which can improve readability and maintainability of the code. By requiring named function expressions, the rule helps ensure that stack traces are more informative, making debugging easier.
The rule allows for configuration to adapt to different project needs, including options to always require names, never require names, or require names only when needed (‘as-needed’). This flexibility allows teams to choose the most appropriate setting for their development practices, ensuring that the rule aligns with their specific code style guidelines.
It takes into account different contexts in which a function expression might not need a name, such as when the function name would be inferred in an ES6 environment. This reduces the likelihood of unnecessary warnings for functions that are implicitly named by their context, allowing developers to focus on more significant issues in their code.
The rule includes logic to skip checking for recursive functions by determining if the function’s name is being used within the function itself. This prevents false positives in scenarios where naming the function is necessary for recursion, ensuring that the rule does not discourage valid and necessary coding patterns.
func-style
Enforce the consistent use of either function
declarations or expressions
Consistency in codebase: This ESLint rule ensures that a project consistently uses either function declarations or function expressions (including the allowance of arrow functions if configured) throughout its entire codebase. Such consistency improves readability and reduces confusion for developers working on or entering the project.
Configurability for modern JavaScript syntax: The rule’s option to allow arrow functions while enforcing either function expressions or declarations gives projects the flexibility to adopt modern JavaScript practices in a controlled manner. This helps in maintaining the modernity of the codebase without compromising on the established code style guidelines.
Detects and enforces style at both declaration and usage: By checking not only the declaration but also the usage context of functions (e.g., whether they’re used in a variable declarator or as an export), this rule ensures that the function style adheres to the project’s guidelines in various scenarios, enhancing code consistency even in complex patterns.
Improves the ‘this’ keyword handling: The rule’s mechanism to track ThisExpression
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
Enforce line breaks between arguments of a function call
function-paren-newline
Enforce consistent line breaks inside function parentheses
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
Enforce consistent spacing around *
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
Enforce return
statements in getters
Ensures that getter functions, which are expected to return a value, fulfill their intended purpose by enforcing the inclusion of a return statement. This prevents silent failures or unexpected behavior in the program due to getters that perform actions but do not return a value.
Allows for the configuration flexibility to either mandate explicit returns in all getter functions or permit implicit returns, catering to different coding style preferences or project requirements while maintaining the rule’s core objective.
Enhances code readability and maintainability by promoting a consistent structure within getter functions, making them easier to understand at a glance. This consistency helps new developers or contributors to quickly grasp the purpose and behavior of getters in the codebase.
Helps in identifying unreachable or dead code segments within getter functions, thereby aiding in debugging and optimizing the code by removing or refactoring parts that do not contribute to the expected output of the getter.
global-require
Require require()
calls to be placed at top-level module scope
require()
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
Require grouped accessor pairs in object literals and classes
guard-for-in
Require for-in
loops to include an if
statement
This rule ensures that the for-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.
By enforcing an 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.
The rule helps maintain consistency across the codebase by establishing a specific pattern for iterating over object properties. This can aid in code readability and maintainability, as developers can quickly understand the intended logic without needing to guess whether the loop was supposed to iterate over own properties or include inherited ones as well.
It implicitly encourages developers to think about the implications of iterating over properties, potentially leading to a deeper understanding of JavaScript’s prototypal inheritance and the differences between enumerating over an object’s own properties compared to all enumerable properties found along its prototype chain.
handle-callback-err
Require error handling in callbacks
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
Disallow specified identifiers
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
Disallow specified identifiers
id-length
Enforce minimum and maximum identifier lengths
id-match
Require identifiers to match a specified regular expression
implicit-arrow-linebreak
Enforce the location of arrow function bodies
indent-legacy
Enforce consistent indentation
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
Enforce consistent indentation
index
init-declarations
Require or disallow initialization in variable 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
Enforce the consistent use of either double or single quotes in JSX attributes
This rule enforces consistency in quotes usage within JSX attributes which can improve readability and maintainability of the code by establishing a uniform coding style. Consistency in coding practices is especially crucial in projects with multiple developers to avoid unnecessary stylistic changes in code reviews.
By providing an automatic fix option, it reduces the workload on developers and minimizes the potential for human error when manually replacing quotes to adhere to the project’s style guidelines. This automation feature enhances developer productivity and focus by allowing them to concentrate on more critical issues in the code.
The rule helps prevent potential bugs related to the incorrect usage of quotes in JSX attributes. While JSX syntax closely resembles HTML, it has distinct differences that could lead to errors if not properly handled; consistent quote usage as enforced by this rule aids in mitigating such risks.
It supports configurability to prefer either double or single quotes, thus allowing teams to align the rule with their existing coding standards or personal preferences without enforcing a one-size-fits-all approach. This flexibility is vital for adopting the rule across a variety of projects with different stylistic guidelines.
key-spacing
Enforce consistent spacing between keys and values in object literal properties
This rule ensures consistency in the way keys and values are spaced within object literals, making the code easier to read and maintain. By dictating whether spaces should exist before or after the colon, it eliminates variations in style that can cause unnecessary focus on formatting during code reviews.
The rule offers a level of customization for alignment options, allowing teams to enforce either a vertical alignment based on the colon or the value. This flexibility lets teams adhere to a coding standard that best matches their readability preferences and existing coding styles.
By providing auto-fix capabilities, this rule not only highlights inconsistencies but also simplifies the process of correcting them. Developers can automatically adjust spacing around colons in object literals without manually altering each instance, speeding up both the development and the code review process.
The rule’s ability to form groups of properties and check for vertical alignment within those groups helps maintain a clean, organized structure in object literals. This organizational aspect is particularly beneficial in large objects where maintaining readability can become challenging, ensuring that related properties are styled in a cohesive manner.
keyword-spacing
Enforce consistent spacing before and after keywords
line-comment-position
Enforce position of line comments
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
Enforce consistent 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
Require empty lines around comments
The rule ensures that comments are adequately separated from surrounding code, thereby improving readability and making the code easier to understand for all developers, especially those who may be new to the project.
By enforcing empty lines around comments, this rule helps in visually distinguishing the comments from the code blocks, making it easier to identify comment sections at a glance without them getting lost in the code.
The rule accommodates various programming constructs, like classes, blocks, and arrays, by providing specific options to either allow or disallow empty lines around comments in these contexts, offering flexibility to adhere to different coding standards or preferences.
It provides functionality to ignore specific patterns within comments, allowing developers to specify exceptions to the rule. This is particularly useful for auto-generated comments or code regions where the usual empty line requirement around comments might not be desirable or necessary.
lines-around-directive
Require or disallow newlines around directives
lines-between-class-members
Require or disallow an empty line between class members
logical-assignment-operators
Require or disallow logical assignment operator shorthand
Enhances code readability by using shorthand logical assignment operators (e.g., ||=
, ??=
) 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.
Helps to reduce the risk of typos or logical errors that can occur when manually typing out the longer form of these logical assignments (e.g., 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.
Encourages consistency across codebases by enforcing a specific style for logical assignments. Whether the chosen mode is “always” use shorthand or “never” use shorthand, adhering to one style helps maintain uniformity, making the code easier to follow and maintain by different developers or teams.
Offers conditional fixes and suggestions that are context-aware (e.g., avoiding changes that would alter the meaning of the code if the target of the assignment could be a getter, or if comments are present within the expression). This careful approach ensures that automated code fixes introduced by ESLint do not unintentionally introduce side effects or change the program’s behavior, particularly in nuanced situations like mixing ??
with ||
/&&
, or when dealing with potentially problematic code constructs such as with statements or strict mode considerations.
max-classes-per-file
Enforce a maximum number of classes per file
Encourages single responsibility principle: By enforcing a maximum number of classes per file, this rule directly encourages developers to adhere to the single responsibility principle. It ensures that each class is focused on a specific functionality, improving code readability and maintainability.
Facilitates easier code navigation: When there is only one class per file, it becomes significantly easier for developers to locate and navigate to the code they need to work on. This is especially beneficial in larger projects where searching for specific classes could otherwise become cumbersome.
Enhances code clarity: Limiting the number of classes per file reduces clutter and makes the file’s purpose and functionality clearer to anyone reading the code. This can be particularly helpful for new team members trying to familiarize themselves with a project, as understanding the structure and responsibilities of classes becomes straightforward.
Improves refactoring and testing: With only a single class per file, refactoring code and writing tests become simpler and less error-prone. Developers can easily identify which files need to be updated when a class changes, and unit tests can be more clearly associated with the class being tested. This can lead to better testing practices and a more stable codebase overall.
max-depth
Enforce a maximum depth that blocks can be nested
max-len
Enforce a maximum line length
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
Enforce a maximum number of lines of code in a function
max-lines
Enforce a maximum number of lines per file
max-nested-callbacks
Enforce a maximum depth that callbacks can be nested
max-params
Enforce a maximum number of parameters in function definitions
max-statements-per-line
Enforce a maximum number of statements allowed per line
max-statements
Enforce a maximum number of statements allowed in function blocks
multiline-comment-style
Enforce a particular style for multiline comments
multiline-ternary
Enforce newlines between operands of ternary expressions
Improves Code Readability: Applying this rule forces a consistent structure in multiline ternary expressions, which inherently makes complex logic easier to read and understand. When each operand is on its separate line, it becomes clearer what the condition, true case, and false case are, reducing cognitive load when scanning code.
Enhances Maintainability: With standardized formatting, future modifications to any part of the ternary expression become simpler. Developers can easily insert or remove conditions or outcomes without disturbing the overall layout of the code block, ensuring that updates do not introduce formatting inconsistencies.
Minimizes Merge Conflicts: In collaborative environments, consistent code formatting, especially for conditional logic, can reduce the occurrence of merge conflicts. Since this rule enforces a specific structure, it’s less likely that different formatting preferences among team members will lead to conflicts in version control systems.
Facilitates Automated Tooling: The rule’s design allows for automatic enforcement and fixing of formatting issues related to multiline ternary expressions. This not only saves time during code reviews by reducing manual nitpicking over style but also allows integration with continuous integration/continuous deployment (CI/CD) pipelines to ensure code style consistency across the codebase without human intervention.
new-cap
Require constructor names to begin with a capital letter
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
Enforce or disallow parentheses when invoking a constructor with no arguments
newline-after-var
Require or disallow an empty line after variable declarations
newline-before-return
Require an empty line before return
statements
return
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
Require a newline after each call in a method chain
ignoreChainWithDepth
option to meet their specific needs, tailoring the rule enforcement to match preferred coding guidelines.no-alert
Disallow the use of alert
, confirm
, and prompt
Improves user experience: Usage of methods like 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.
Enhances application security: Historically, these dialog methods have been prone to misuse, such as phishing attempts through spoofed dialogs. By disallowing these methods, the rule indirectly contributes to mitigating certain types of security risks.
Promotes modern web standards: The shift away from 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.
Facilitates better debugging and logging practices: Replacing methods like 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
Disallow Array
constructors
This rule enforces the use of more readable and concise syntax for creating arrays, such as using array literals ([]
) instead of the Array
constructor. This makes the code easier to understand, especially for those new to JavaScript or coming from other programming languages.
It helps prevent potential confusion or errors when using the 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.
The rule includes a fix suggestion mechanism that not only identifies the less preferred usage but also provides developers with an immediate suggestion on how to rectify it. This can improve development efficiency by reducing the time spent on manual code reviews for such patterns.
By enforcing a uniform way of creating arrays across the codebase, it can enhance code consistency and quality. When developers follow a standardized approach, it reduces the cognitive load required to understand different sections of the code, leading to a more maintainable and scalable codebase.
no-async-promise-executor
Disallow using an async function as a Promise executor
Prevents the common anti-pattern of using an async function as a Promise executor, which can lead to unhandled promise rejections. This specifically addresses issues where exceptions thrown in the async executor function are not properly caught by the surrounding code, leading to potential debugging challenges and runtime errors that are harder to track down.
Promotes the use of more standard and predictable patterns for creating new Promises. By disallowing async functions within the executor, it encourages the use of then/catch chaining or the async/await syntax outside of the executor function, which aligns with more conventional JavaScript promise handling practices.
Enhances code readability and maintainability by steering developers away from a pattern that might seem convenient but actually introduces complexity. The rationale behind this rule directly targets reducing the cognitive load for developers by advocating for more straightforward and universally understood promise creation and handling patterns.
Increases the robustness of error handling in asynchronous operations. The rule ensures that errors are explicitly handled through reject or caught in a catch block, rather than potentially disappearing into the void due to the quirks of async functions as promise executors. This is particularly important in environments where reliability and error transparency are crucial.
no-await-in-loop
Disallow await
inside of loops
The rule no-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.
By disallowing 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.
It helps in spotting unintentional serial execution of what could be parallel tasks. Developers might not always realize that using 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.
This rule can lead to the adoption of better coding practices by enforcing the consideration of alternative approaches to achieving the same goal without compromising on performance. For example, refactoring code to use 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
Disallow bitwise operators
This rule specifically helps in maintaining code readability and understandability. Bitwise operators can be obscure to some developers, especially those not familiar with low-level programming concepts, and using more descriptive methods or operations can improve the clarity of what the code is intended to do.
By discouraging the use of bitwise operators, this rule fosters writing code that is less prone to subtle bugs. It’s easy to misuse bitwise operators or misunderstand their effects, especially in high-level programming tasks, leading to errors that are difficult to diagnose.
The rule implicitly encourages the use of JavaScript’s standard library functions (e.g., 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.
It allows for exceptions through its configuration options, making it adaptable for cases where bitwise operations are justified or necessary, such as performance-sensitive code or when interfacing with binary data. This ensures that developers are not overly restricted where there is a valid use case for these operators.
no-buffer-constructor
Disallow use of the Buffer()
constructor
The rule targets the prevention of using the deprecated Buffer()
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.
It encourages using safer alternatives like 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.
Enforcing this rule assists in future-proofing the codebase, considering Node.js has officially deprecated the use of the old 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.
The rule not only identifies the deprecated usage but also suggests modern, safer alternatives which can lead to both faster execution times (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
Disallow the use of 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
Disallow lexical declarations in case clauses
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
Disallow catch
clause parameters from shadowing variables in the outer scope
Prevents confusion and improves code readability by ensuring that catch clause parameters have unique names, avoiding confusion with variables in the outer scope. This is particularly important in complex try-catch structures where shadowing could lead to misunderstanding which variable is being referenced.
Enhances debuggability by ensuring the integrity of variable values in the outer scope. If a catch clause inadvertently shadows an outer scope variable, during debugging, it might appear that the outer scope variable’s value is changing, when in fact, it’s the catch clause’s parameter that is being altered.
Contributes to cleaner code maintenance and refactoring by explicitly disallowing shadowing in catch clauses, thus preventing potential bugs that might arise in the future when the code is modified or extended. This rule forces developers to choose unique names, leading to a more thoughtful naming strategy and potentially more descriptive variable names.
Supports good programming practices in languages like JavaScript where scopes can be easily misunderstood or overlooked. By ensuring that catch parameters do not shadow outer variables, it indirectly educates developers about scope management and encourages practices that make the code more predictable and easier to understand for new developers or during code reviews.
no-class-assign
Disallow reassigning class members
no-compare-neg-zero
Disallow comparing against -0
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
Disallow assignment operators in conditional expressions
This rule helps prevent accidental assignments in conditional expressions, which are a common source of bugs. For example, using =
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.
By enforcing this rule, developers are encouraged to write clearer and more intentional conditional logic. The requirement to enclose assignments within parentheses if they are to be used in a conditional expression makes the developer’s intent explicit, both to the JavaScript engine and to anyone reading the code.
The rule supports a configurable option ("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.
It improves code readability and maintainability by ensuring that conditional expressions are straightforward and easy to understand at a glance. By disallowing assignments in conditionals or requiring them to be explicitly wrapped in parentheses, the codebase becomes more uniform and less prone to errors, making it easier for new developers to understand the code and for teams to maintain it over time.
no-confusing-arrow
Disallow arrow functions where they could be confused with comparisons
The rule prevents the confusion between arrow functions and comparison operators in code. For instance, 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.
By offering the option to require parentheses around the function body when using conditional expressions, it enforces a clearer syntax, making it immediately obvious that the expression is intended to be the return value of the arrow function, not a comparison. This leads to cleaner and more understandable code, especially for those who may be newer to JavaScript or coming from a different programming background.
The configurable options 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.
The rule helps in automated code refactoring and consistency across a codebase by providing a fix mechanism that can automatically adjust arrow functions to include parentheses where necessary. This reduces manual effort in code review and maintenance, ensuring that all arrow functions conform to the team’s style guide with minimal developer intervention.
no-console
Disallow the use of 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
Disallow reassigning const
variables
const
, 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
Disallow expressions where the operation doesn’t affect the value
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
Disallow constant expressions in conditions
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
Disallow returning value from constructor
This rule helps enforce the standard JavaScript behavior where constructors implicitly return the newly created object, ensuring consistency across your codebase. By disallowing explicit returns, it prevents confusion among developers about what a constructor is supposed to do, which is to initialize the object, not to decide what to return.
It prevents potential errors in object creation, as returning anything other than the current instance (this) from a constructor will replace the instance one might expect to receive. This is particularly important in cases where an explicit return might inadvertently return the wrong value or type, leading to bugs that are difficult to trace.
The rule encourages the use of proper error handling within constructors by blocking return statements. This pushes developers to use exceptions for error signaling in constructors (e.g., using throw
for invalid input values) instead of returning null or any other value, thereby promoting a more robust error handling strategy.
Ensuring that constructors do not return values helps in maintaining clarity and readability of the code. It makes the behavior of constructors predictable, as they solely focus on instance initialization. This rule, therefore, aids in enforcing a coding standard that aligns with the expectations of JavaScript’s object-oriented design principles.
no-continue
Disallow continue
statements
The no-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
.
It promotes the practice of handling conditions explicitly within the loop’s logic itself, rather than skipping iterations. This explicitness can lead to more readable and maintainable code, as the conditions for proceeding with the loop’s body are directly tied to the logic within the loop, rather than being negated and skipped.
By disallowing the use of 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.
The rule fosters the development of alternative solutions that may have performance benefits. In certain cases, redesigning loop logic to avoid 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
Disallow control characters in regular expressions
no-debugger
Disallow the use of 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
Disallow deleting variables
Enforces a better understanding of variable deletion and its effects in JavaScript, specifically preventing developers from attempting to delete variables which is not a valid operation in JavaScript. This helps maintain the integrity of the execution environment by avoiding errors at runtime due to improper deletion attempts.
Encourages the use of proper techniques for removing or clearing data. For instance, setting a variable to 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.
This rule highlights the correct usage of the 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.
Prevents potential memory leaks and ensures cleaner, more predictable code. By disallowing the deletion of variables, which JavaScript does not support as expected, developers are guided towards practices that do not lead to unintended side effects or the misuse of language features.
no-div-regex
Disallow equal signs explicitly at the beginning of regular expressions
/=
) 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
Disallow duplicate arguments in function
definitions
no-dupe-class-members
Disallow duplicate class members
no-dupe-else-if
Disallow duplicate conditions in if-else-if chains
no-dupe-keys
Disallow duplicate keys in object literals
no-duplicate-case
Disallow duplicate case labels
no-duplicate-imports
Disallow duplicate module imports
no-else-return
Disallow else
blocks after return
statements in if
statements
Improves Readability: Using the no-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.
Reduces Code Complexity: By enforcing the removal of unnecessary 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.
Promotes Early Exit Pattern: The rule implicitly promotes the use of the early exit (or guard clause) pattern, where conditions that lead to terminating the function are handled at the beginning, and the main body of the function follows without being nested within else
blocks. This pattern can enhance the function’s clarity and maintainability.
Avoidance of Unintentional Scope Leaks: Since this rule encourages refactoring code to eliminate unnecessary 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
Disallow empty character classes in regular expressions
This rule helps in identifying and preventing syntax errors in regular expressions that can lead to unexpected matches or no matches at all. An empty character class, as indicated in the “bad” example, does not match any character and could be a developer’s oversight.
It enhances the readability and maintainability of the code by ensuring that all character classes in regular expressions are explicitly defined. This makes the regular expressions more understandable to new developers or others revisiting the code.
By disallowing empty character classes, it aids in avoiding potentially costly runtime errors or inefficient execution of regular expressions, as the JavaScript engine might spend time evaluating an expression that logically cannot match any character.
The rule indirectly educates developers about correct regular expression syntax and practices by pointing out a common mistake. This educational aspect can improve overall code quality and developer skill in writing more effective and error-free regular expressions.
no-empty-function
Disallow empty functions
This ESLint rule specifically targets empty functions across different syntaxes, including traditional function declarations, function expressions, and arrow functions, ensuring a uniform enforcement throughout the codebase. It helps in maintaining code quality by disallowing functions that do nothing, which can be confusing or misleading to developers, thereby promoting the use of meaningful, action-oriented functions.
The rule allows for customization through options, enabling teams to specify exceptions where an empty function might be permissible according to their project needs. This flexibility ensures that teams can adapt the rule to fit specific scenarios, such as stubbing out functions for future implementation or when using lifecycle methods in frameworks that don’t require an implementation body.
By checking for the absence of both code and comments within the body of the function, the rule encourages developers to either implement the function or provide explanatory comments about why the function is intentionally left empty. This practice improves code readability and maintainability, making it easier for others to understand the purpose of empty functions or the intention behind leaving them as placeholders.
Implementing this rule and adhering to its guidance can help in reducing potential bugs in the software development process. Empty functions can sometimes be a result of incomplete refactoring or placeholders forgotten by developers. By flagging these instances, the rule assists in preemptively identifying areas of the code that may require further attention or completion, thus contributing to a more robust development cycle.
no-empty-pattern
Disallow empty destructuring patterns
The rule helps prevent the use of empty destructuring patterns that can lead to confusion or suggest an incomplete implementation. When developers see an empty pattern, they might wonder if it’s intentional or a mistake, leading to unnecessary code review comments or assumptions.
By disallowing empty destructuring patterns, this rule enforces more deliberate code writing practices. Developers are encouraged to clearly state their intentions, making code easier to understand. For example, if one intends to use variables from an object or array, they should explicitly list them, improving code readability and intention clarity.
The rule offers configurability with the 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.
It directly addresses potential performance concerns by encouraging the removal of unnecessary operations. Destructuring with empty patterns could lead to unnecessary work, such as copying properties or elements that are never used. By enforcing the use of non-empty patterns, it ensures that every destructuring operation has a clear purpose, contributing to more efficient code.
no-empty-static-block
Disallow empty static blocks
no-empty
Disallow empty block statements
This rule helps maintain code clarity by ensuring that block statements, which inherently imply the execution of statements, are not misleadingly left empty without explanation. It prevents developers from creating blocks of code that do nothing, thereby avoiding confusion for future maintenance or review by other developers.
It makes an exception for specific scenarios like allowing empty catch blocks if configured (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.
The rule supports code readability and documentation by suggesting the inclusion of comments within empty blocks. This encourages developers to explicitly state the rationale behind leaving a block empty, thereby not leaving room for speculation about whether the empty block is a mistake or intentional.
It emphasizes good coding practices by also covering switch statements with no cases, encouraging developers to refactor their code for better readability and maintainability. This ensures that switch statements serve their purpose of handling multiple cases and are not misused or left incomplete.
no-eq-null
Disallow 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
Disallow the use of 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
Disallow reassigning exceptions in catch
clauses
catch
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
Disallow extending native types
no-extra-bind
Disallow unnecessary calls to .bind()
The rule helps ensure that .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.
By disallowing unnecessary .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
.
It encourages developers to understand and correctly use the scope and context (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.
It incorporates automated fixing for violations, which not only helps in educating developers about unnecessary .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
Disallow unnecessary boolean casts
!!
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
Disallow unnecessary labels
The ‘no-extra-label’ rule helps in maintaining code clarity by disallowing unnecessary labels that could otherwise clutter the code and make it harder to read. Labels that are not needed for the logical flow of the program are identified and removed, making the code more straightforward for other developers to understand.
It aids in the optimization of JavaScript execution. While modern JavaScript engines are highly optimized, unnecessary labels can still introduce a minor overhead in parsing. By removing these unnecessary labels, the rule ensures that the JavaScript code is as lean and efficient as possible.
This rule prevents potential errors in large codebases where labels might be reused inappropriately or might lead to confusion regarding the scope of breaks and continues. By ensuring that only necessary labels are used, it reduces the possibility of control flow errors that can be hard to debug.
It promotes best practices in coding by encouraging developers to use control structures in a clear and logical manner without relying on unnecessary labeled statements. This can be particularly helpful for new developers learning to write clean code and for maintaining a high quality of code in collaborative projects where consistency is key to readability and maintainability.
no-extra-parens
Disallow unnecessary parentheses
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
Disallow unnecessary semicolons
It eliminates syntax redundancy by removing unnecessary semicolons, which can improve code readability and maintain a cleaner codebase. Specifically, it targets semicolons that do not contribute to the code’s functionality, as demonstrated in the examples where semicolons after function declarations and for loops are identified as superfluous.
The rule includes logic to determine if a semicolon is fixable, considering nuanced cases where removal of a semicolon could change the meaning of subsequent strings into directives. This careful consideration ensures that the fix applied does not inadvertently alter the program’s correct behavior, making automation both safer and more reliable.
By reporting unnecessary semicolons within class bodies and after method definitions explicitly, it aids in enforcing coding style consistency specifically in object-oriented structures. This is crucial as the complexity of class definitions might lead to more frequent stylistic inconsistencies, making focused rules like this valuable for maintaining uniformity.
It provides an automated fixing mechanism that is context-aware, meaning it only suggests or implements fixes where the removal of the semicolon would not lead to syntax errors or misunderstood expressions. This automation supports faster code refactoring, allowing developers to focus on more complex problems instead of manually fixing stylistic issues.
no-fallthrough
Disallow fallthrough of case
statements
This rule helps in maintaining the integrity of switch
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.
The rule can improve code readability and maintainability. For developers reading the code, it becomes immediately clear whether the fallthrough is intentional or not. If the fallthrough is intentional, the expectation is that it will be accompanied by a comment explaining why. This makes the code easier to understand and maintain over time.
It allows for some flexibility through configuration options, such as 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.
By checking for comments that explain intentional fallthroughs and allowing configuration of the comment pattern, this rule encourages developers to document their code better. This not only improves the immediate understandability of the code but also helps in long-term maintenance as future developers can understand the reasoning behind certain coding decisions.
no-floating-decimal
Disallow leading or trailing decimal points in numeric literals
.5
is transformed into 0.5
, and 123.
is transformed into 123.0
.no-func-assign
Disallow reassigning function
declarations
Prevents confusion and potential bugs that can occur when a function declaration is reassigned. For instance, if a developer accidentally reassigns a function, it could lead to unexpected behavior or runtime errors.
Maintains function declaration immutability within the codebase, ensuring that declared functions remain constant throughout the lifecycle of the application. This immutability concept is especially important in larger projects where tracking function behavior is critical.
Enhances code readability and maintainability by enforcing a clear and consistent structure for function usage. When functions are not reassigned, their behavior is easier to predict, making the code easier to understand and debug.
Aids in static analysis by enabling tools like ESLint to more accurately understand and predict the code’s behavior, since the reassignment of functions can complicate the control flow and scope resolution, leading to less precise analysis outcomes.
no-global-assign
Disallow assignments to native objects or read-only global variables
no-implicit-coercion
Disallow shorthand type conversions
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
Disallow declarations in the global scope
no-implied-eval
Disallow the use of eval()
-like methods
eval()
-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
Disallow assigning to imported bindings
This ESLint rule prevents accidental or intentional alterations to imported bindings, ensuring that module interfaces remain consistent and predictable across different parts of the application. Modifying imported bindings can lead to subtle bugs and unexpected behavior as it goes against the design of ES6 module semantics, where imports are read-only.
The rule aids in code maintainability and readability by enforcing clearer distinctions between locally declared variables and imported bindings. When developers are prevented from assigning to imported bindings, they are encouraged to use more straightforward and understandable patterns for managing state and dependencies.
It supports the principle of immutability for imported modules, which can lead to safer code. Immutable data patterns are easier to reason about and debug. By enforcing this rule, developers are nudged towards adopting these beneficial practices, leading to fewer side effects and unpredictable state changes in the codebase.
The rule is particularly useful in large codebases or in projects with multiple contributors, where tracking the origin and flow of data can become challenging. By ensuring that imported bindings remain unchanged, it simplifies the task of understanding how data flows through the application and how different modules interact with each other. This can significantly reduce the time required for new developers to familiarize themselves with the codebase and for existing developers to track down bugs or implement new features.
no-inline-comments
Disallow inline comments after code
Promotes readability by enforcing a clear separation between code and comments, ensuring that comments do not clutter the side of the code. This separation can make the code easier to read, especially for complex logic where inline comments might disrupt the flow of understanding.
Helps maintain a consistent code commenting style across a project, which can be particularly beneficial in team environments where multiple developers contribute to the codebase. Consistency in how comments are made improves the overall code quality and collaboration.
Increases the chance that comments will be more thoughtful and explanatory rather than just being quick annotations that might not fully explain the reasoning behind the code. When developers are encouraged to place comments above the line of code, they may take a moment to provide more context or clarification.
Avoids potential issues with language syntaxes or tooling that might misinterpret inline comments, especially in complex scenarios involving multiple languages or preprocessors where inline comments could inadvertently affect the execution or processing of code.
no-inner-declarations
Disallow variable or function
declarations in nested blocks
no-invalid-regexp
Disallow invalid regular expression strings in RegExp
constructors
u
and v
), thus aligning with ECMAScript specifications and ensuring broader compatibility and predictability of regex behavior across different JavaScript engines.no-invalid-this
Disallow use of 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
Disallow irregular whitespace
This ESLint rule is specifically tailored to identify and report irregular whitespace characters that can cause issues in code readability, and potentially lead to problematic bugs that are hard to spot during code review. By automating the detection of such characters, this rule ensures that all whitespace in the codebase follows a consistent pattern, which is a crucial aspect for maintaining high code quality.
The rule provides configurable options to skip certain areas where irregular whitespace might be intentionally used or where its presence doesn’t impact the execution or readability of code, such as comments, strings, regular expressions, template literals, and JSX text. This level of granularity allows teams to apply strict whitespace conventions without disrupting workflows where exceptions to the rule are justified, thereby balancing code quality with practical coding scenarios.
By filtering out irregular whitespace in literals, regular expressions, templates, and JSX text based on developer preferences, this rule not only enhances the readability and consistency of code but also respects the context-specific needs of different types of code constructs. This ensures that automatic linting does not interfere with intentional design or formatting decisions that may rely on specific whitespace characters in these contexts.
The rule contributes to the overall maintainability and readability of the codebase by enforcing a standardized approach to handling whitespaces. Regular spacing is easier to read, understand, and debug, especially for teams working in collaborative settings or when the code is handed off to new developers. Consistency in code formatting, including whitespace usage, is a key aspect of code quality that can significantly impact developer productivity and the long-term sustainability of a project.
no-iterator
Disallow the use of the __iterator__
property
This ESLint rule specifically targets and disallows the use of the non-standard __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.
Implementing this rule helps in avoiding potential runtime errors or unexpected behavior in browsers or environments that do not support the __iterator__
property, thereby improving the reliability of the code.
By disallowing the __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.
Enforcing this rule can aid in codebase modernization efforts, by identifying and discouraging outdated and non-standard practices. As the JavaScript language evolves, adopting standard and future-proof iteration methods over proprietary or deprecated ones is beneficial for long-term code health and interoperability.
no-label-var
Disallow labels that share a name with a variable
no-labels
Disallow labeled statements
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
Disallow unnecessary nested blocks
let
and const
declarations within unnecessary blocks, which might behave differently than the developer expects if misunderstood.no-lonely-if
Disallow if
statements as the only statement in else
blocks
if
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
Disallow function declarations that contain unsafe references inside loop statements
Ensures that functions defined within loops do not inadvertently reference loop variables from an outer scope, which can lead to bugs, especially with asynchronous code. This prevents unexpected behaviors by ensuring variables are properly scoped.
Improves code maintainability by encouraging the use of patterns that make the scope and lifetime of variables clear, reducing the cognitive load on developers trying to understand the flow of variables within loops.
Helps to identify instances where variables may change value before a function is executed, particularly relevant in asynchronous operations like setTimeout
, mitigating issues related to closures capturing loop variables.
Encourages best practices in JavaScript development by highlighting a common mistake, enhancing code quality, and potentially leading to performance improvements by avoiding unnecessary closures within loops.
no-loss-of-precision
Disallow literal numbers that lose precision
no-magic-numbers
Disallow 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
Disallow characters which are made with multiple code points in character class syntax
The rule helps to identify characters in regular expressions that are made with multiple code points and might not be interpreted correctly without the proper flags, specifically the Unicode u
flag. This ensures that developers do not unintentionally write regular expressions that fail to match intended characters.
It automatically suggests a fix by adding the 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.
By enforcing the use of the 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.
The rule educates developers about the importance of correctly handling Unicode characters in JavaScript, which might otherwise be overlooked. It brings attention to an aspect of JavaScript and regular expression syntax that is crucial for internationalization and working with modern web applications that handle diverse character sets.
no-mixed-operators
Disallow mixed binary operators
5 + 10 * 3 - 2
could confuse readers about the sequence of operations.(5 + (10 * 3)) - 2
.no-mixed-requires
Disallow require
calls to be mixed with regular variable declarations
The rule enforces a clean and organized code structure by avoiding the mixture of require
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.
By allowing options like 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.
It indirectly promotes the use of modern JavaScript practices by highlighting the separation and explicit declaration of dependencies at the top of the file or function scope. While not preventing the use of 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.
The rule comes with a built-in logic to distinguish between different types of 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
Disallow mixed spaces and tabs for indentation
no-multi-assign
Disallow use of chained assignment expressions
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
Disallow multiple spaces
no-multi-str
Disallow multiline strings
Ensures code consistency and readability: Multiline strings using backslashes can be confusing and less readable, especially for developers new to the codebase or those not familiar with this particular JavaScript syntax. Enforcing a standard for multiline strings helps maintain code consistency and improves readability, making it easier for team members to read and understand code quickly.
Helps avoid runtime errors: Multiline strings defined with backslashes might lead to hard-to-detect errors in the code, especially if a developer accidentally removes or mismatches a backslash. By disallowing multiline strings in this manner, this rule helps preempt potential runtime errors that could be caused by such mistakes, contributing to the overall stability of the application.
Encourages the use of template literals or concatenation: By disallowing multiline strings, developers are encouraged to use template literals or string concatenation instead. These alternatives are part of modern JavaScript and offer clearer syntax and functionality for defining multiline strings, including variable interpolation in the case of template literals, which can lead to more expressively written code.
Adapts to JSX considerations: The rule is designed with exceptions for JSX elements, acknowledging the unique syntax and requirements of JSX when it comes to dealing with strings. This nuance ensures that the rule doesn’t inadvertently enforce a restriction in contexts where multiline strings might be necessary or more common, such as within JSX elements, allowing developers to write JSX code efficiently without compromising on the specific needs of UI development within React or other JSX-utilizing libraries.
no-multiple-empty-lines
Disallow multiple empty lines
no-native-reassign
Disallow assignments to native objects or read-only global variables
window
or undefined
, which could lead to severe implications for the application’s functionality.no-negated-condition
Disallow negated conditions
no-negated-in-lhs
Disallow negating the left operand in in
expressions
Prevents confusion when reading code that checks for the non-existence of a property within an object. Since !'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.
Enhances code readability and clarity by ensuring the negation applies to the entire operation rather than just to the left operand. The correct pattern !('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.
Helps in maintaining consistency across the codebase by enforcing a pattern for negating conditions which involve the in
operator. This reduces the likelihood of mistakes that could arise from developers using different patterns for similar checks.
Could potentially prevent subtle bugs related to precedence. In JavaScript, the 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
Disallow nested ternary expressions
Prevents decreased readability: Nested ternary operators, especially when they span multiple lines or are part of complex expressions, can significantly decrease code readability. This rule ensures that each conditional logic is clear and straightforward, making the code easier for developers to read and understand.
Facilitates easier debugging: Debugging issues within nested ternary operations can be challenging due to the condensed way in which the conditionals are presented. By disallowing nested ternaries, this rule promotes structuring conditionals in a way that can be more easily stepped through with a debugger.
Encourages better maintainability: Code that is easier to read and understand is naturally easier to maintain. With the disallowance of nested ternary expressions, developers are encouraged to write more maintainable code by using clearer alternatives like if-else statements, which can be quickly adjusted or extended without the complexity of untangling nested conditionals.
Enhances team collaboration: In team environments, code consistency and clarity are paramount. By enforcing a rule against nested ternary expressions, the team adopts a uniform approach to writing conditional logic. This alignment helps prevent misunderstandings or the need for rewrites when code passes between team members, ultimately improving collaboration and efficiency.
no-new-func
Disallow new
operators with the Function
object
Function
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
Disallow new
operators with global non-constructor functions
new
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
Disallow 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
Disallow new
operators with calls to require
This rule specifically targets the prevention of using the 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.
Enforcing this rule ensures that modules are loaded as intended by their authors. Using 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.
Application performance can be indirectly affected. Instantiating a required module with 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.
It promotes code readability and maintainability. By adhering to a common pattern for module importation (i.e., using 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
Disallow new
operators with the Symbol
object
Ensures compliance with ECMAScript specification: The JavaScript specification defines the Symbol
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.
Prevents runtime exceptions: Utilizing 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.
Educates developers: For developers unfamiliar with the unique nature of 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.
Maintains consistency in codebase: By enforcing the creation of symbols using 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
Disallow 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
Disallow new
operators outside of assignments or comparisons
new
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
Disallow \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
Disallow calling global object properties as functions
This rule directly targets a common misunderstanding among JavaScript developers where global objects like 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.
It enhances code readability and maintainability by ensuring that global objects are used correctly according to their intended purpose. For instance, distinguishing between correct (Math.round(5.76)
) and incorrect (Math(5.76)
) usage guides developers to follow best practices in the use of built-in JavaScript objects.
The rule not only checks for direct calls on global objects but also tracks the referencing of these objects in a way that might lead to calling them incorrectly. This includes deep references and incorrectly invoking them as constructors, covering a broader spectrum of potential mistakes than just direct invocation.
By providing specific feedback through context.report with messageId and data detailing the name of the global object being misused, developers are not left guessing what part of their code violated the rule. This direct feedback loop can significantly speed up the debugging process and educate developers about the correct usage patterns of global objects in JavaScript.
no-object-constructor
Disallow calls to the 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
Disallow octal escape sequences in string literals
no-octal
Disallow octal literals
071
), it might be interpreted as an octal number rather than a decimal, affecting the program’s logic unexpectedly.no-param-reassign
Disallow reassigning function
parameters
This ESLint rule specifically targets a common programming pitfall where function parameters are reassigned or their properties are modified within the function body. Such practices can lead to unexpected behaviors in code, as they modify the state of arguments outside the scope of the function, potentially affecting other parts of the program that rely on the original object or value.
It provides options to customize the enforcement of this rule, such as allowing property modifications for certain variables or ignoring modifications that match specific patterns. This flexibility ensures that the rule can be adapted to different coding styles and requirements, making it practical for a wide range of projects without forcing an all-or-nothing approach.
The rule’s focus on preventing assignments to function parameters and their properties encourages the use of functional programming principles, such as immutability and pure functions. This can lead to more predictable and maintainable code, as it avoids side effects and makes functions easier to reason about, test, and debug.
By enforcing the creation and use of new objects or variables instead of modifying existing function parameters, the rule indirectly promotes better state management and data flow in applications. This practice can enhance code readability and maintainability, as it makes it clear when and where data is transformed or updated.
no-path-concat
Disallow string concatenation with __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
Disallow the unary operators ++
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
Disallow the use of process.env
The rule 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.
By discouraging the direct use of 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.
The rule helps in establishing a uniform standard across the team or project by ensuring that all developers access environment variables in the same way. This promotes consistency and reduces the chances of errors that could arise from a developer unintentionally bypassing any security or validation layers implemented for accessing these variables.
Implementing this rule as part of the project’s ESLint configuration aids in early detection of code that directly accesses 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
Disallow the use of 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
Disallow returning values from Promise executor functions
The rule specifically targets a common misunderstanding of how Promise executor functions are supposed to work by preventing the return of values from these functions, which can lead to unexpected behavior or bugs in Promise-related code. This is crucial for maintaining the integrity of asynchronous code flows.
By disallowing returns from Promise executors unless explicitly voided (with the 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.
The rule provides automatic suggestion fixes, such as prepending 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.
It considers various scenarios and syntax styles (like checking for ArrowFunctionExpression and handling void expressions differently based on the 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
Disallow the use of the __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
Disallow calling some Object.prototype
methods directly on objects
Object.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
Disallow variable redeclaration
The 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.
This rule is also important for identifying unintentional redeclarations that could overwrite variables due to hoisting in JavaScript, where variable declarations are moved to the top of their scope. Such redeclarations can cause unexpected results, especially in complex scopes.
By including the capability to identify redeclarations of both syntax and built-in globals, the rule enhances the robustness of the code. It prevents overshadowing of global variables or inadvertently redeclaring them, which can lead to confusing behavior or conflicts in the runtime environment.
The rule offers configurability (e.g., considering or ignoring built-in globals through options) that can be tailored to the project’s needs, ensuring that projects that rely on global variables, including those defined in browser or Node.js environments, can adjust the rule to fit their specific requirements. This adaptability helps in enforcing project-specific best practices without sacrificing the benefits of the rule.
no-regex-spaces
Disallow multiple spaces in regular expressions
The rule specifically targets and identifies multiple consecutive spaces within regex expressions, which are often hard to count or spot visually in code reviews or even during a casual glance at the code. This specificity helps in maintaining regex clarity and accuracy, which is crucial given the nuanced and error-prone nature of regex syntax.
By converting these multiple spaces into a quantified form (e.g., ” ”), it enforces a clearer and more maintainable approach to expressing spaces in regular expressions. This conversion can prevent misunderstandings or mistakes regarding the intended number of spaces, especially in large or complex regex patterns.
The rule includes a mechanism for safely attempting to fix detected violations by replacing consecutive spaces with their quantified form only when the pattern is exactly represented in the source code, reducing the risk of erroneous automatic fixes that could alter the regex’s intended behavior.
It smartly avoids false positives by excluding spaces within character classes and by not reporting consecutive spaces that are syntactically significant but outside the purview of what should be flagged (e.g., within strings meant to be used as regex but not directly representing regex patterns). This nuanced handling respects regex syntax rules and developer intentions, ensuring that only meaningful and correctable instances are reported.
no-restricted-exports
Disallow specified names in exports
no-restricted-globals
Disallow specified global variables
no-restricted-imports
Disallow specified modules when loaded by import
no-restricted-modules
Disallow specified modules when loaded by require
The rule helps enforce a project’s or team’s coding standards by disallowing the use of specific modules that might be considered harmful, outdated, or incompatible with the project’s architecture or security policies. For instance, preferring a more secure module over the Node.js ‘fs’ module for file operations.
It allows for custom error messages to be associated with restricted modules or patterns, providing developers with clear guidance and rationale for why a certain module is disallowed. This educational feedback can improve code quality and adherence to project standards over time.
By supporting both specific module names and pattern matching for module paths, the rule offers flexibility in defining restricted modules. This can be particularly useful in large codebases or projects with complex dependencies, allowing for a granular control over which modules can be used.
The rule’s design to allow relative path imports while restricting certain modules or patterns means that project structures can remain flexible and local module usage can be encouraged. This can promote the use of project-specific modules or libraries that conform to project standards, while still ensuring that potentially harmful external modules are avoided.
no-restricted-properties
Disallow certain properties on certain objects
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
Disallow specified syntax
This rule promotes the use of more modern, efficient, and less error-prone syntax by allowing teams to block older syntax that may lead to bugs or performance issues. For example, using for...of
instead of for...in
for arrays to avoid unintended property enumeration.
By providing the capability to define custom error messages, this rule facilitates clearer communication within a team about why certain syntaxes are discouraged, thereby aiding in educational efforts and improving codebase maintainability.
It enhances code consistency and readability across large projects by enforcing a standardized way of coding. For instance, consistently using array methods like .map()
, .forEach()
, etc., instead of various loop constructs for array operations.
The rule’s flexibility in defining restricted syntax through strings or objects with custom messages allows for precise targeting of problematic code patterns specific to the project’s requirements, which makes it a valuable tool for enforcing best practices and coding standards tailored to the project.
no-return-assign
Disallow assignment operators in return
statements
This ESLint rule specifically targets the prevention of using assignment operators directly within return
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.
The rule helps in avoiding subtle bugs that might occur when a developer unintentionally uses an assignment in a return statement, thinking it’s a comparison or another operation. This is especially relevant in JavaScript, where the similarity between assignment (=
) and equality operators (==
and ===
) can lead to errors that are hard to debug.
By enforcing the separation of actions (assignment and returning a value) into distinct statements, the rule encourages better code structure and readability. This makes it easier for other developers, or even the original author after some time, to understand the flow and purpose of the code, as each operation is explicitly stated rather than implied.
In cases where developers might intentionally use assignments in return statements for brevity, this rule forces them to reconsider their approach towards maintaining code consistency and clarity. It nudges the developer towards patterns that are widely accepted as more readable and maintainable, thus indirectly enforcing best practices within the codebase.
no-return-await
Disallow unnecessary return await
The rule helps in improving code readability by avoiding redundancy. Specifically, using 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.
It can potentially lead to performance optimizations. While the redundant use of 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.
By flagging unnecessary 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.
The rule offers automatic fix suggestions that can streamline the code refactoring process. This means developers can quickly adjust their code according to the rule’s recommendations without manually searching and removing unnecessary await
keywords, thus speeding up the development process and ensuring code style consistency across the codebase.
no-script-url
Disallow javascript:
urls
This rule helps in reducing security risks associated with the injection of malicious scripts. By disallowing the use of “javascript:” URLs, which can execute JavaScript code directly from hyperlinks, it mitigates potential attack vectors for cross-site scripting (XSS) attacks.
It enforces better coding practices by encouraging developers to use safer, more modern methods for event handling and interactivity, such as adding event listeners to DOM elements, instead of embedding JavaScript code within URL strings.
The rule promotes code clarity and maintainability. By preventing the use of “javascript:” URLs, which can make JavaScript logic harder to trace and debug, it encourages developers to structure their code in a more organized and readable manner, with JavaScript functionality clearly separated from HTML structure.
It ensures compatibility and functionality across different web browsers and environments. “javascript:” URLs are not universally supported in the same way across all platforms and can lead to inconsistent behavior. Enforcing alternative methods of implementing interactive features helps in achieving more consistent and predictable outcomes across various user agents.
no-self-assign
Disallow assignments where both sides are exactly the same
This ESLint rule, ‘no-self-assign’, directly prevents a common coding mistake where a variable is assigned to itself, which is usually unintended and indicative of a misunderstanding or typo. Implementing this rule can catch such errors early in the development process, thereby reducing debugging time and improving code quality.
By disallowing self-assignments, which are effectively no-ops (no operation), the rule helps in optimizing the codebase. Removing redundant operations can lead to slight improvements in runtime performance and resource usage, particularly in critical code paths or loops.
Using this rule encourages developers to scrutinize their use of assignment operators. Since it checks for self-assignment with not only the basic assignment operator (=
) but also with compound assignment operators like &&=
, ||=
, and ??=
, it educates developers about the proper usage of these operators and promotes coding best practices.
It improves code readability and maintainability by eliminating unnecessary lines of code. For someone reading the code, self-assignments might be confusing and could lead to the misconception that a more complex operation is being performed. By ensuring that such assignments are flagged and removed, the rule aids in keeping the codebase cleaner and more understandable.
no-self-compare
Disallow comparisons where both sides are exactly the same
This ESLint rule, ‘no-self-compare,’ specifically targets and identifies instances in the code where a variable is being compared to itself. Such comparisons are logically redundant as they will always return true, except in the unique case of NaN values in JavaScript. By catching these, it ensures that developers do not unintentionally write code that could be confusing or misleading to others, or that simply performs unnecessary operations.
By disallowing self-comparisons, this rule helps to highlight a common misunderstanding about how certain values, particularly NaN, behave in JavaScript. Since NaN is not equal to any value, including itself, using a self-comparison to check for NaN is the only valid use case. The rule encourages developers to explicitly check for NaN using isNaN() instead, leading to clearer and more correct code.
Utilizing the ‘no-self-compare’ rule aids in the optimization of the codebase. While modern JavaScript engines are very efficient at optimizing code at runtime, removing redundant comparisons can contribute to slightly faster execution times and a reduction in the overall running cost of the code, especially in large-scale applications where such checks might be numerous.
The rule includes a fix suggestion by demonstrating a meaningful replacement for a self-comparison when checking for NaN. This not only helps in correcting the error but also serves as an educational tool for developers, teaching them a more appropriate method for achieving their intended outcome. Moreover, through the encouragement of best practices and cleaner code, it indirectly contributes to the overall reliability and maintainability of the project.
no-sequences
Disallow comma operators
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
Disallow returning values from setters
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
Disallow identifiers from shadowing restricted names
This rule prevents the confusion that arises when developers redefine or shadow globally restricted names such as 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.
By disallowing the shadowing of restricted names, the rule enforces more readable and understandable code. When a restricted name is used, readers can be confident it refers to the global, well-known value rather than a local variable, reducing the cognitive load when understanding the code.
It helps in maintaining consistency and predictability across the codebase. For example, tools or libraries that rely on the global arguments
object or the eval
function will work as expected without being inadvertently affected by local redefinitions.
The rule indirectly encourages developers to choose more descriptive and meaningful names for their variables. Instead of lazily naming a variable 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
Disallow variable declarations from shadowing variables declared in the outer scope
no-spaced-func
Disallow spacing between function identifiers and their applications (deprecated)
no-sparse-arrays
Disallow sparse arrays
This ESLint rule specifically targets the use of sparse arrays, which are arrays with empty slots between elements, exemplified by the bad example [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.
By disallowing sparse arrays and suggesting the use of explicitly defined values (like 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.
The rule helps maintain code quality by enforcing explicitness in array definitions. Sparse arrays can be a source of errors, especially for developers who may not be aware that JavaScript arrays can contain empty slots. These errors might come from operations that behave differently on dense versus sparse arrays, such as map()
and forEach()
, which will skip over empty slots in sparse arrays.
The automatic reporting feature of this rule, where it uses 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
Disallow synchronous methods
This ESLint rule specifically targets the elimination of synchronous methods, which can improve the non-blocking nature of node.js operations. By disallowing methods ending with “Sync”, it ensures that code adheres to asynchronous patterns, enhancing performance especially in I/O bound applications.
The rule provides a clear mechanism to report the use of synchronous methods by leveraging a selector that matches member expressions ending in “Sync”. This specificity helps developers identify and refactor synchronous calls to asynchronous counterparts, promoting better error handling and response times in applications.
It includes an option (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.
By enforcing the refactoring of synchronous methods to their asynchronous alternatives, as demonstrated in the provided ‘fix’ example, this rule aids in preventing common pitfalls associated with blocking operations. It encourages the use of Promises and async/await syntax, which can lead to more readable and maintainable code, especially in complex, event-driven applications.
no-tabs
Disallow all 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
Disallow template literal placeholder syntax in regular strings
This rule helps to avoid unintentional use of template literal syntax in regular strings, which does not lead to interpolation. For example, it flags instances where a developer might accidentally use ${variable}
inside quotes, expecting the variable to be substituted, but since it’s not a template literal, it wouldn’t work as intended.
It promotes the correct usage of ES6 template literals when variable substitution within strings is desired. By enforcing template literals (using backticks) for variable interpolation, it ensures that developers use a syntax that will actually evaluate and insert variable values as expected.
The rule assists in preventing hard-to-find bugs related to string handling. Since the usage of ${}
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.
It aids in code clarity and maintainability by enforcing a consistent approach to string interpolation. By distinguishing between regular strings (for static text) and template literals (for dynamic text), it makes the developer’s intention clear, improving readability for others who might work on the same codebase.
no-ternary
Disallow ternary operators
no-this-before-super
Disallow this
/super
before calling super()
in constructors
super()
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
Disallow throwing literals as exceptions
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
Disallow trailing whitespace at the end of lines
Enforces a cleaner code base by eliminating trailing whitespace, which is not visually apparent but can cause unnecessary changes in version control. Trailing spaces are often invisible in many code editors and can be introduced inadvertently, leading to diffs that consist of whitespace changes only. This rule helps avoid such scenarios, making code reviews more focused on actual code changes rather than formatting issues.
Increases compatibility with tools that automatically strip trailing spaces, reducing the chance of introducing spurious differences in files. Some editors or tools have settings to remove trailing spaces on save, which can lead to unintended file changes if a project’s contributors use different development environments. Consistently disallowing trailing spaces with this ESLint rule can minimize such discrepancies.
Supports optional configurability for ignoring trailing spaces on blank lines and within comments, allowing teams to tailor the rule to their coding standards or to gradually enforce it without immediately impacting every single line of code. This flexibility can be particularly useful during the transition period when a codebase is being cleaned up or when adopting new coding styles and guidelines.
Integrates automated fixing, allowing developers to automatically correct offending lines without manual intervention. This feature significantly reduces the effort required to comply with the rule, encouraging its adoption and ensuring code consistency with minimal developer effort. It’s particularly beneficial for legacy codebases undergoing formatting standardization, as it permits mass correction without the need for extensive manual code edits.
no-undef-init
Disallow initializing variables to undefined
The rule helps in cleaning up the code by avoiding redundant initializations. Since variables in JavaScript are 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.
By enforcing this rule, it aims to improve code readability. Removing unnecessary initializations to 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.
The rule indirectly enforces a good practice of relying on the language’s default behaviors, in this case, the default 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.
This rule comes with an automated fix option for certain cases, which can save developers time during refactoring or code reviews by automatically removing unnecessary initializations. This automation helps maintain a cleaner codebase without requiring manual intervention for this specific type of issue.
no-undef
Disallow the use of undeclared variables unless mentioned in /*global */
comments
This rule helps in identifying variables that are used in the code but have not been declared, reducing runtime errors due to undefined variables. This ensures that all variables are properly initialized before use, enhancing code reliability and maintainability.
By optionally allowing the use of undeclared variables when they are explicitly mentioned in /*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.
The rule’s option to consider or ignore identifiers within a 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.
Through the reporting mechanism tied to the specific identifier causing the violation, developers are directly pointed to the source of potential bugs, enabling quicker fixes and reducing the time spent debugging issues related to undeclared variables. This targeted feedback loop is crucial for maintaining high code quality, especially in larger projects where such issues can easily go unnoticed.
no-undefined
Disallow the use of undefined
as an identifier
undefined
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
Disallow dangling underscores in identifiers
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
Disallow confusing multiline expressions
no-unmodified-loop-condition
Disallow unmodified loop conditions
Prevents the risk of infinite loops which can occur if the loop condition variables are not modified within the loop. In the provided “bad” example, the variable attempts
is not modified inside the loop, which could potentially lead to an infinite loop if checkInput
never returns true
.
Enhances code readability and maintainability by ensuring that loops are written with clear progression criteria, making it easier for developers to understand how and when the loop will terminate.
Helps identify logical errors at an early stage, where a developer might have unintentionally forgotten to update the loop condition. This rule flags such lapses, enabling quick fixes that could otherwise lead to hard-to-debug runtime issues.
Encourages best practices in programming by enforcing a pattern where the conditions for loop continuation are actively controlled within the loop body, promoting the writing of safer and more efficient code.
no-unneeded-ternary
Disallow ternary operators when simpler alternatives exist
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
Disallow loops with a body that allows only one iteration
The rule specifically targets loop constructs that are set up in such a way that they can only iterate once before hitting a condition that forces them to exit. This is particularly useful to identify and correct loops that, due to their logic, do not fulfill their intended iterative purpose which can help developers catch logical errors or inefficiencies in their code early.
By identifying loops that will only run once, this rule helps in optimizing the performance of the code. Unnecessary loops can add overhead by setting up loop controls and evaluating conditions which ultimately are redundant, thereby wasting computational resources.
The rule helps in improving code readability and maintainability by pointing out sections of the code that are logically complex or have misleading constructs. For example, a loop that only runs once might suggest an algorithm that could be simplified or a misunderstanding of how loop constructs work, leading to clearer and more maintainable code once addressed.
It reduces the risk of introducing subtle bugs related to the misunderstanding of loop behavior. A developer might expect a loop to process multiple elements or perform iterations under certain conditions, but due to misconfiguration, it exits prematurely. Highlighting these scenarios ensures the loop’s logic aligns with the developer’s intentions, thereby reducing the likelihood of bugs related to control flow.
no-unreachable
Disallow unreachable code after return
, throw
, continue
, and break
statements
The rule specifically targets and eliminates unreachable code that follows return
, 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.
By disallowing unreachable code, it directly contributes to cleaner codebases, making maintenance and debugging easier. When developers understand that certain sections of code are guaranteed not to be executed, they can focus on optimizing and debugging the reachable parts of their code more effectively.
The rule includes logic to handle various statement types, including function declarations, class declarations, loops, and conditional statements, which makes it comprehensive in detecting unreachable code across a wide array of JavaScript syntax. This thoroughness ensures that most, if not all, cases of unreachable code can be identified and reported, regardless of the specific control flow constructs used.
It incorporates a sophisticated way of tracking code paths and segments, including managing current code path segments and distinguishing consecutive statements. This allows for accurate identification and reporting of unreachable code, even in complex code structures. By doing so, it helps maintain high code quality standards and supports best practices in programming by ensuring that control flow in applications is logical and efficient.
no-unsafe-finally
Disallow control flow statements in finally
blocks
Ensures predictability in error handling: Using control flow statements like return
, 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.
Improves code readability and maintainability: By disallowing control flow statements in 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.
Prevents unintended consequences: The use of control flow statements in 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.
Encourages proper usage of 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
Disallow negating the left operand of relational operators
This rule helps to prevent logical errors in the code where developers might unintentionally negate the left operand of relational operators (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
.
It enhances code readability and maintainability by enforcing a clearer syntax for negations with relational operators. By requiring explicit parentheses when intending to negate the result of a relational operation, it becomes immediately clear to anyone reading the code what the intended logic was, reducing the cognitive load and potential for misinterpretation.
The rule includes a suggestion mechanism that can automatically fix detected issues by adding parentheses where necessary. This feature can save developer time and reduce the likelihood of human error during manual correction, making code refactoring and review processes more efficient.
By allowing configuration options such as 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
Disallow use of optional chaining in contexts where the undefined
value is not allowed
Ensures arithmetic operations are safe by preventing the addition of undefined
values which can lead to NaN errors. For instance, const result = obj?.b + 5;
might result in undefined + 5
without this rule.
Enhances code readability and maintainability by enforcing the explicit handling of potentially undefined
values when using optional chaining, which can otherwise lead to unexpected behaviors or bugs.
Promotes the use of nullish coalescing operator (??
) over logical OR (||
) with optional chaining to explicitly handle undefined
and null
values, ensuring that fallback values are used only in the intended cases.
Prevents the erroneous return of 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
Disallow 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
Disallow unused labels
no-unused-private-class-members
Disallow unused private class members
This rule helps identify and remove private class members (like methods and properties) that are declared but not used within the class. By enforcing the removal of unused private members, it ensures that the class code remains clean and concise, improving code readability and maintainability.
It reduces the overall memory footprint of your application. Unused private class members, particularly methods, can still occupy memory space even if they are never invoked. Removing these can lead to a slight performance improvement, especially in large applications with many class definitions.
The rule discourages the practice of leaving dead code in the project, which can cause confusion for developers. When a new developer encounters an unused private member, they might spend unnecessary time figuring out its purpose or hesitate to remove it due to uncertainty about its relevance, slowing down development.
Enforcing this rule can also indirectly encourage better coding practices and architecture decisions. When developers know that unused private members will be flagged, they are more likely to carefully plan their class designs and member usage, leading to more thoughtfully constructed and efficient codebases.
no-unused-vars
Disallow unused variables
no-use-before-define
Disallow the use of variables before they are defined
Prevents potential ReferenceErrors caused by using variables or functions before their declaration, improving the reliability of the code. By ensuring all references are defined before use, this rule helps avoid runtime errors that are difficult to debug.
Enhances code readability and maintainability by enforcing a more predictable structure. When variables and functions are defined before they are used, it becomes easier for developers to follow the flow of logic within the codebase, making the code easier to understand and maintain.
Supports the correct understanding and use of the Temporal Dead Zone (TDZ) for let and const declarations in JavaScript. By disallowing the use of variables before they are defined, this rule helps developers avoid subtle bugs related to the TDZ, where let and const variables exist but aren’t initialized.
Allows for more efficient code optimization by JavaScript engines. When variables and functions are used after they are defined, it becomes easier for JavaScript engines to optimize the code, potentially leading to performance improvements in the execution of the code.
no-useless-backreference
Disallow useless backreferences in regular expressions
^(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
Disallow unnecessary calls to .call()
and .apply()
The rule specifically targets the elimination of redundant usage of .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.
By detecting and discouraging the use of .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.
Since .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.
The rule also indirectly educates developers about the correct use cases for .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
Disallow unnecessary catch
clauses
no-useless-computed-key
Disallow unnecessary computed property keys in objects and classes
Promotes code cleanliness by discouraging the use of unnecessary computed property keys, leading to more readable and straightforward object and class syntax. When property names are statically determinable, using computed keys adds unnecessary complexity.
Enhances code performance slightly; accessing properties using computed keys is a tad slower than accessing them directly. By discouraging unnecessary computed keys, this rule may contribute to micro-optimizations, especially in performance-critical applications.
Prevents potential bugs related to using dynamic property names when static ones are intended. In some cases, developers might use computed keys by habit or misunderstanding, potentially leading to unintended dynamic behavior. By enforcing simpler syntax, this rule helps maintain the intended static nature of property definitions.
Improves auto-fixable coding patterns, allowing developers to automatically clean up and simplify their code bases with tooling support. This rule comes with an auto-fix option that can correct violations without manual intervention, thereby saving time and reducing the potential for human error during refactoring or code review processes.
no-useless-concat
Disallow unnecessary concatenation of literals or template literals
Ensures code readability by eliminating the need to decipher unnecessary string concatenations, which can simplify understanding string values at a glance. For example, instead of piecing together several concatenated pieces, a developer can see the intended string in one cohesive unit.
Improves performance by reducing the number of runtime concatenation operations, especially relevant in tight loops or high-performance code sections. Concatenating literals at compile time can shave off precious milliseconds in critical performance paths.
Encourages the use of template literals for variable inclusion within strings, prompting developers towards modern JavaScript features that enhance code clarity and functionality. This also indirectly promotes consistency in how dynamic strings are handled across the codebase.
Helps in identifying potentially unintended concatenations that could be a result of typos or logic errors, thus preventing bugs related to string processing. For example, it flags cases where developers might accidentally concatenate strings that were meant to be separate entities, thus allowing early correction.
no-useless-constructor
Disallow unnecessary constructors
no-useless-escape
Disallow unnecessary escape characters
no-useless-rename
Disallow renaming import, export, and destructured assignments to the same name
This rule helps maintain code clarity and simplicity by eliminating redundant syntax, which can make the code less verbose and easier to read. Renaming an import, export, or destructured assignment to the same name adds unnecessary complexity without any benefit.
It ensures consistency across the codebase by preventing developers from using an unnecessary rename syntax. This consistency can be particularly beneficial for teams working on large projects, as it makes the code more homogenous and understandable for everyone involved.
By disallowing unnecessary renaming, this rule can indirectly prevent potential typos or errors that might occur during the renaming process. For example, when manually renaming variables, there’s a risk of introducing a typo that could lead to bugs. Not needing to rename reduces this risk.
The rule provides automatic fix capabilities for detected issues, which can save developer time and effort. When the rule detects unnecessary renaming, it can automatically correct it to the simpler syntax without renaming. This automated fix reduces the manual work required and helps in maintaining cleaner code more efficiently.
no-useless-return
Disallow redundant return statements
Ensures cleaner code by eliminating redundant return statements, which in turn may make the code easier to read and maintain. For instance, removing unnecessary return;
statements at the end of functions simplifies the function’s logic.
Helps in potentially reducing the cognitive load for developers reading the code by removing statements that have no effect on the code’s execution. This can also make it easier to understand the intended control flow of the function.
By flagging useless return statements, it encourages developers to consider the necessity of their control flow statements. This could lead to more thoughtful coding practices, where developers aim for concise and efficient code.
May indirectly improve performance in certain JavaScript engines by reducing the number of instructions that need to be executed. Although the impact might be minimal, removing unnecessary statements contributes to overall code optimization.
no-var
Require let
or const
instead of var
Promotes block-scoped variable declarations: This rule enforces the use of 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.
Encourages immutable data patterns: By requiring 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.
Prevents temporal dead zone (TDZ) issues: This rule includes logic to check for self-references in the TDZ, which is the time after hoisting but before the variable is initialized. Given that 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.
Minimizes scope-related errors: The detailed conditions under which the rule does not automatically fix a 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
Disallow void
operators
void
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
Disallow specified warning terms in comments
no-whitespace-before-property
Disallow whitespace before properties
This rule ensures consistency in object property access notation by disallowing whitespace before the dot or bracket notation, making the code more readable and easier to understand. For example, turning object .property
or array [index]
into object.property
or array[index]
, which is the standard notation.
The rule prevents syntax errors and potential runtime issues that may arise from unusual whitespace usage before properties, such as when attempting to call a method on a number literal with a space (5 .toString()
), ensuring the integrity of the code’s execution.
It automates the removal of unintended whitespaces in property access expressions, which not only cleans up the code but also saves time during code review and manual refactoring processes, maintaining a cleaner and more professional codebase.
The rule is designed to be intelligent by not applying fixes in certain cases where it could introduce errors or when comments exist between tokens, thereby respecting the developer’s intentions and possibly highlighting unconventional use cases that warrant a manual review.
no-with
Disallow with
statements
with
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
Enforce the location of single-line statements
This ESLint rule enforces a consistent styling for where single-line statements should be located relative to their control statements (such as 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.
By providing configuration options that allow teams to enforce single-line statements either beside or below their control statements (or allow any position), this rule offers flexibility to adhere to an organization’s specific coding standards. Such adaptability ensures that the rule can be tailored to the preferences of different teams or projects, promoting a uniform coding style that aligns with organizational best practices.
The rule includes an automatic fix feature, which can correct misaligned single-line statements according to the configured preference (either to the ‘beside’ or ‘below’ position). This automated fixing capability can save developers time during both the development and code review processes by reducing manual effort required to adhere to styling rules and allowing them to focus more on logic and functionality rather than formatting inconsistencies.
The scope of this rule covers several control statement types (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
Enforce consistent line breaks after opening and before closing braces
object-curly-spacing
Enforce consistent spacing inside braces
The rule assists in maintaining a uniform appearance of object literals, destructuring assignments, and import/export specifiers across a codebase by enforcing or forbidding spaces inside the curly braces, which can lead to improved readability and easier maintenance due to consistency.
It automatically corrects detected violations by adding or removing spaces as appropriate, thereby saving time during code reviews and reducing the burden on developers to manually fix style issues related to brace spacing.
By offering configurable exceptions for arrays and objects within objects, the rule provides flexibility, allowing teams to adopt a spacing policy that best suits their preferences for certain complex structures while still enforcing a general rule.
The rule helps prevent potential merge conflicts and diff noise in version control systems caused by inconsistent spacing inside braces among different code contributions, thus facilitating smoother collaboration and integration processes.
object-property-newline
Enforce placing object properties on separate lines
object-shorthand
Require or disallow method and property shorthand syntax for object literals
one-var-declaration-per-line
Require or disallow newlines around variable declarations
one-var
Enforce variables to be declared either together or separately in functions
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
Require or disallow assignment operator shorthand where possible
The rule encourages the use of assignment operator shorthand (+=
, *=
, %=
, 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.
It includes a mechanism to safely apply fixes that take into account both the presence of comments between tokens and the precedence of operations, ensuring that automatic corrections do not unintentionally change the logic of the code. This careful approach minimizes the risk of introducing bugs when the rule’s suggestions are applied.
The rule differentiates between commutative and non-commutative operations, allowing it to identify cases where shorthand can be applied without altering the execution order of expressions. This distinction is crucial for maintaining the correctness of operations that depend on the order of operands (e.g., a = b * a
being different from a *= b
in certain contexts).
It offers configurability to enforce or prohibit the use of operator assignment shorthands, allowing teams to adopt the style that best suits their codebase. This flexibility makes the rule adaptable to various coding guidelines and preferences, enabling teams to enforce consistency in code style regarding assignment operations.
operator-linebreak
Enforce consistent linebreak style for operators
padded-blocks
Require or disallow padding within blocks
The rule helps in enforcing a consistent code format regarding padding within blocks, switches, and classes. This means that depending on the project’s coding standards, it can require or disallow empty lines at the beginning and end of a block, thus making the code more readable and maintaining a standard look across the codebase.
It provides a configurable option to allow single-line blocks without padding, which can be particularly useful for short, simple blocks of code where padding might make the code unnecessarily lengthy or visually cluttered.
The rule’s design to check and potentially auto-fix padding in different structures (blocks, switches, classes) makes it versatile and applicable to various aspects of JavaScript programming, ensuring that all parts of the code can adhere to the specified padding rules.
Since the rule includes options to automatically fix violations by adding or removing padding as necessary, it can save developers time during the coding process and help reduce the potential for manual errors, making the code cleaner and more efficient to execute.
padding-line-between-statements
Require or disallow padding lines between statements
By enforcing consistent padding lines between statements, this rule significantly improves the readability of the code, making it easier for developers to distinguish between separate blocks of logic or sections of code. In the provided “fix” example, the visual separation between variable declaration, console logs, and the conditional statement clearly delineates the distinct actions being performed.
The rule aids in maintaining a uniform code style across a project, or even across teams if the configuration is shared. This uniformity reduces cognitive load when switching between files or projects, as developers can expect a consistent structure in how code is formatted, specifically regarding the spacing between statements.
It prevents likely merge conflicts and simplifies code reviews by standardizing the amount of whitespace between statements. Code differences that result from disparate uses of padding lines (for instance, one developer using two newline characters where another uses one) can create unnecessary merge conflicts. By enforcing a specific style, this rule helps to minimize such avoidable issues.
The rule is configurable to match different coding styles and preferences, improving its adaptability to various projects or team guidelines. Since it can interpret array of configurations for matching different types of statements (e.g., variable declarations, function calls, if statements), it offers flexibility in enforcing line padding in a way that aligns with the unique stylistic choices or readability goals of a project. This adaptability ensures that teams can enforce padding where it’s most beneficial without compromising on the broader stylistic choices of their codebase.
prefer-arrow-callback
Require using arrow functions for callbacks
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
Require const
declarations for variables that are never reassigned after declared
const
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
Require destructuring from arrays and/or objects
prefer-exponentiation-operator
Disallow the use of 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
Enforce using named capture group in regular expression
prefer-numeric-literals
Disallow parseInt()
and Number.parseInt()
in favor of binary, octal, and hexadecimal literals
This ESLint rule encourages the use of binary, octal, and hexadecimal literals instead of parseInt()
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.
The rule includes an autofix feature that automatically replaces calls to 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.
By disallowing 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.
It carefully checks that replacing 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
Disallow use of Object.prototype.hasOwnProperty.call()
and prefer use of Object.hasOwn()
Avoids indirect method access: The rule discourages the use of 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.
Encourages modern method adoption: Promoting the use of 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.
Improves performance potential: While the exact performance implications can depend on JavaScript engine optimizations, using 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.
Increases code safety and readability: By enforcing the use of 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
Disallow using Object.assign with an object literal as the first argument and prefer the use of object spread instead
Ensures modern JavaScript syntax is used: By preferring the use of object spread ({...obj}
) over Object.assign({}, obj)
, this rule encourages the adoption of ES6+ syntax, which is more concise and readable for merging objects.
Improves performance: Object spread syntax can lead to performance improvements in many JavaScript engines compared to Object.assign
when merging objects, as it’s more optimized for this specific use case.
Reduces unnecessary complexity: Using object spread simplifies the syntax and avoids the verbosity of Object.assign
, particularly when the first argument is an empty object literal. This can make code easier to read and maintain.
Avoids unintended side effects: When using 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
Require using Error objects as Promise rejection reasons
prefer-reflect
Require Reflect
methods where applicable
Encourages the use of Reflect
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.
Helps in avoiding some of the pitfalls and inconsistencies associated with the traditional methods like 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.
Facilitates operations on objects without directly invoking their internal methods, serving as a safer alternative for operations like property deletion (Reflect.deleteProperty
vs delete
operator). This is particularly useful in scenarios involving proxied objects, where direct operations might inadvertently trigger traps.
Provides an opportunity to easily configure exceptions for specific cases where the developer might intentionally prefer the traditional method over 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
Disallow use of the RegExp
constructor in favor of regular expression literals
RegExp
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
Require rest parameters instead of 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
Require spread operators instead of .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
Require template literals instead of string concatenation
The rule promotes the use of template literals over string concatenation, which leads to more readable and maintainable code, especially when embedding variables within strings. For instance, the rule would transform "Your full name is: " + firstName + " " + lastName + "."
into Your full name is: ${firstName} ${lastName}.
, which is easier to comprehend at a glance.
It automatically handles escaping of characters that might otherwise be interpreted as part of the template syntax (${}
and backticks), when converting string concatenations into template literals. This reduces the risk of introducing syntax errors or unintended behavior during the conversion process.
By encouraging the use of template literals, this rule indirectly supports better string formatting practices, such as multiline strings and including expressions within strings without the need for concatenation operators (+
). This can lead to cleaner code, particularly when dealing with long strings or strings that require dynamic content.
The rule provides autofix functionality, meaning that in many cases, it can automatically convert code that uses string concatenation to use template literals instead. This not only saves developer time but also helps in enforcing a consistent coding style across a codebase without requiring manual intervention for such conversions.
quote-props
Require quotes around object literal property names
This rule caters specifically to enhancing code readability and consistency by requiring quotes around object literal property names, making it easier for developers to distinguish between property names and other language constructs.
It helps avoid potential errors by ensuring that keywords or reserved words that happen to be used as object property names are quoted, which is especially helpful to maintain compatibility across different ECMAScript versions or environments where an identifier might be interpreted incorrectly.
The rule’s options allow for flexibility between quoting all property names, quoting as needed (only when it would otherwise result in a syntax error or misinterpretation), or maintaining consistency throughout the object, which can be critical for projects requiring a specific coding style for maintainability and to avoid bikeshedding.
It includes automatic fix capabilities to correct inconsistencies or unnecessary quoting, thereby saving developer time and reducing the likelihood of human error during manual code reviews or corrections, helping to maintain a clean and stylistically consistent codebase with minimal effort.
quotes
Enforce the consistent use of either backticks, double, or single quotes
backticks
, double
, or single
quotes) throughout the codebase, reducing the cognitive load when reading and understanding code.radix
Enforce the consistent use of the radix argument when using parseInt()
Prevents ambiguity in numeric conversions: The radix parameter specifies the base of the numerical string used in 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.
Promotes code readability and maintainability: By requiring the radix argument, it becomes immediately clear to anyone reading the code which numerical base is intended for the conversion. This clarity makes the code easier to understand and maintain, especially for teams or in public code bases where people with different levels of expertise may interact with the code.
Enforces best practices automatically: Instead of relying on manual code reviews or developer memory to ensure the radix is provided, this ESLint rule automates the enforcement. Automatic checks like this help maintain code quality and adhere to best practices without extra effort from developers.
Provides actionable feedback with autofix suggestions: When the rule identifies a violation, it doesn’t just flag the issue but also suggests a fix, specifically to add a radix of 10 for decimal conversions if missing. This not only educates developers about the issue but also provides a quick way to resolve it, improving the development workflow and speeding up the process of addressing linting feedback.
require-atomic-updates
Disallow assignments that can lead to race conditions due to usage of 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
Disallow async functions which have no await
expression
The rule enforces the use of await
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.
By disallowing async functions that do not include an 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.
The rule aids in code readability and maintainability by ensuring that the use of 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.
Enforcing this rule can help in preventing potential errors in the flow of asynchronous code. For example, a developer might mark a function as async with the intention of using await
but forget to do so. This rule would catch such oversights, potentially saving time in debugging asynchronous logic issues.
require-jsdoc
Require JSDoc comments
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
Enforce the use of u
or v
flag on RegExp
u
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
Require generator functions to contain yield
yield
keyword, promoting correctness in asynchronous or iterable operations.rest-spread-spacing
Enforce spacing between rest and spread operators and their expressions
semi-spacing
Enforce consistent spacing before and after semicolons
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
Enforce location of semicolons
Ensures consistency in semicolon placement throughout the code, which can aid in readability and maintenance by following a standardized format, whether at the beginning or the end of lines based on the configured option.
Helps prevent common syntax errors or parsing issues that might occur from incorrect semicolon placement, particularly in languages where semicolons can change how lines or blocks of code are interpreted.
Facilitates easier code minification and concatenation processes, as consistent and correct semicolon placement can prevent runtime errors when scripts are compressed into a single line.
Assists in the automatic fixing of semicolon-related styling issues, thus saving developer time and effort in code reviews or manual corrections, and maintaining a cleaner codebase with less effort.
semi
Require or disallow semicolons instead of ASI
sort-imports
Enforce sorted import declarations within modules
The rule enforces a consistent ordering of import declarations within a module, which can improve readability and maintainability of code. By having a predefined sort order (e.g., “none”, “all”, “multiple”, “single”), developers can easily find and manage imports, reducing the cognitive load when working with modules.
It offers configurable options to ignore case sensitivity and the sorting of member names within import declarations. This flexibility allows teams to tailor the rule to their coding standards and preferences, ensuring that imports are sorted in a way that makes the most sense for their project’s structure and naming conventions.
The rule supports separating import groups with blank lines and resetting the sorting logic per group if configured with 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.
It includes functionality to automatically fix unsorted imports, saving developers time and effort that would otherwise be spent manually sorting imports. This auto-fixing capability streamlines the development process, ensuring that imports adhere to the specified order without requiring manual intervention and thus reducing the chance of human error.
sort-keys
Require object keys to be sorted
sort-vars
Require variables within the same declaration block to be sorted
space-before-blocks
Enforce consistent spacing before blocks
The rule ensures a uniform appearance across the codebase by enforcing or disallowing space before blocks, contributing to increased readability and maintainability. This consistency helps developers quickly understand the structure and flow of the code, regardless of the specific details of each block.
By offering configuration options like “always” or “never” for functions, keywords, and classes, it allows teams to align the rule with their specific coding standards or style guides. This flexibility ensures that the rule adapts to the preferred practices of different development environments, enhancing team cohesion and productivity.
The rule includes logic to avoid conflicts with other spacing-related ESLint rules (e.g., 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.
Through its automatic fix functionality, it not only identifies inconsistencies but also offers the means to correct them automatically. This feature significantly speeds up the process of adhering to the project’s coding standards, as it reduces the manual effort required from developers to align their code with the enforced style rules, thereby allowing them to focus more on solving complex problems rather than on formatting issues.
space-before-function-paren
Enforce consistent spacing before function
definition opening parenthesis
This rule ensures a consistent appearance in code by either enforcing or prohibiting spaces before function parentheses, making the codebase easier to read and maintain. Applying this rule across a project helps to standardize the formatting of function declarations and expressions, including arrow functions, which can reduce cognitive load when reading through code.
It allows for customizable configurations, meaning a team can decide whether they want to always have a space before the parenthesis, never have it, or ignore the rule for certain functions (e.g., async arrow functions, named functions, or anonymous functions). This flexibility lets the rule adapt to a project’s specific coding style preferences or guidelines.
The rule accounts for exceptions and nuances in coding styles, such as not applying fixes if there’s a single-line comment between the function keyword and its parentheses. This consideration helps to maintain the readability and intent of comments without inadvertently introducing syntax errors or misinterpretations of code.
It provides automatic fixing capabilities, which can save developers time during code refactoring or initial writing. For instances where a space is missing and should be added (or vice versa), the rule’s fixer can automatically adjust the code to comply with the project’s chosen configuration, helping to speed up the development process and ensure code style consistency without manual effort.
space-in-parens
Enforce consistent spacing inside parentheses
The rule explicitly enforces a consistent spacing practice inside parentheses across the codebase, which enhances readability and standardizes the format of code for all developers involved. Given the examples, without this rule, code can appear cluttered and inconsistent, making it harder to read and maintain.
It provides flexibility through exceptions, allowing developers to configure the rule to ignore specific cases such as empty parentheses, or when they contain specific characters (, [], ()). This adaptability means that while promoting consistency, the rule can be tailored to fit the particular styling guides or preferences of a project or team.
The rule includes automatic fix functionality that can correct spacing issues by either inserting or removing spaces as needed. This not only saves time during the development process but also helps in ensuring that code complies with the project’s styling guidelines without requiring manual intervention for such stylistic concerns.
The exceptions management within the rule logic allows for fine-tuning the enforcement of spaces within parentheses. For instance, it differentiates between opening and closing parentheses and offers an opportunity to handle empty parentheses differently. This level of detail in exception handling helps in addressing nuanced styling preferences, thereby providing a more customizable and thorough approach to enforcing code style rules specific to spacing within parentheses.
space-infix-ops
Require spacing around infix operators
=
, +
, ?
, :
, 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
Enforce consistent spacing before or after unary operators
The rule specifically targets the enforcement of consistent spacing around unary operators, which is crucial for maintaining readability and a uniform code style. By focusing on both word-based (like 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.
This rule offers configurability for projects through 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.
The inclusion of a fixer function within the rule’s logic enables automatic correction of spacing inconsistencies, saving developers time during code reviews and reducing manual effort required to adhere to stylistic guidelines. This feature significantly increases the utility of this ESLint rule by not only identifying but also resolving spacing issues.
The rule smartly handles special cases, such as the ”!!” for converting a value to a boolean, by including logic to avoid flagging them as errors or attempting an incorrect fix. This attention to detail prevents potential bugs introduced by automated fixes and acknowledges the usage patterns of unary operators in JavaScript, ensuring that the rule does not enforce spacing in a manner that could alter the intended functionality of the code.
spaced-comment
Enforce consistent spacing after the //
or /*
in a comment
This ESLint rule ensures consistency in the use of spacing after comment markers (//
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.
The rule is configurable to accommodate different coding style preferences, either enforcing or disallowing a space immediately after the comment syntax. This flexibility allows teams to adopt a style that best suits their standards and ensures that the linter supports rather than obstructs their preferred coding practices.
It supports automatic fixing of detected issues, which means that developers can quickly correct their code to comply with the enforced style without manually editing each comment. This auto-correction feature not only saves time but also helps maintain consistency throughout the codebase without additional effort from the developers.
The rule handles both line and block comments and is smart enough to consider exceptions and markers. This detailed approach ensures that special cases, such as JSDoc comments or other annotations that might utilize a different spacing rule, are correctly identified and treated according to the project’s configuration. This prevents the misapplication of the rule in contexts where a deviation from the norm is intentional and beneficial for clarity.
strict
Require or disallow strict mode directives
'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
Enforce spacing around colons of switch statements
symbol-description
Require symbol descriptions
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
Require or disallow spacing around embedded expressions of template strings
template-tag-spacing
Require or disallow spacing between template tags and their literals
fix
function can automatically adjust spacing to meet the rule’s requirements without developer intervention.unicode-bom
Require or disallow Unicode byte order mark (BOM)
Ensuring consistency in file encoding across a project: This rule can help enforce a consistent approach to the presence or absence of a Unicode Byte Order Mark (BOM) in project files, reducing potential issues when files are exchanged between different environments and editors that may have differing defaults for handling BOMs.
Facilitating team or project-specific coding standards: By allowing configuration to require or disallow a BOM, this rule supports adherence to agreed coding standards within a team or project, ensuring that all contributors are aligned on this aspect of file formatting.
Avoiding errors related to BOM in JavaScript files: Since the presence or absence of a BOM can affect the way files are parsed and executed in some JavaScript engines or when served to web browsers, enforcing a consistent policy helps prevent subtle, hard-to-diagnose errors related to character encoding.
Automated fixability for easy compliance: The rule offers an automated fix option, capable of inserting or removing the BOM as required. This eases the process of bringing files into compliance with the project’s chosen standard, saving developer time and reducing the likelihood of human error during manual editing.
use-isnan
Require calls to isNaN()
when checking for NaN
This rule specifically addresses the common misconception in JavaScript that 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.
In switch cases, it’s easy to mistakenly include a case for 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
.
When using methods like .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()
.
By enforcing checks for 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
Enforce valid JSDoc comments
@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
Enforce comparing typeof
expressions against valid strings
vars-on-top
Require var
declarations be placed at the top of their containing scope
Ensures a consistent structure within a function or block by having var
declarations at the top. This structure can make the code easier to read and understand, since variable declarations are not scattered throughout the function.
Helps in avoiding potential hoisting issues. JavaScript hoists 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.
Facilitates the identification of variables that are being used throughout a function or block scope. When variables are declared at the beginning, it provides a clear list of what variables are available, improving code maintainability and reducing the chance of redeclaring variables.
Can contribute to slightly improved performance in JavaScript engines that optimize based on the predictability of the code’s structure. While modern engines are efficient at optimizing various patterns, consistent patterns like declaring variables at the top could theoretically make the initial parsing phase slightly faster.
wrap-iife
Require parentheses around immediate function
invocations
The rule enforces a consistent syntax for wrapping immediately invoked function expressions. By either requiring parentheses around the IIFE itself or around the function expression and its invocation, it promotes readability and maintainability of code that uses IIFEs for scoping or executing functions immediately.
It provides options for flexibility in styling—either “inside” or “outside” wrapping of the parentheses. This allows teams or projects to choose the style that best suits their readability preferences or to align with their established coding standards, thus supporting consistency across the codebase.
The rule includes an option to include function prototype methods like call
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.
It offers auto-fix functionality that automatically adjusts the positioning of parentheses to conform to the selected style. This feature saves developers time during both the initial writing and subsequent code reviews by reducing manual effort in formatting and ensuring consistency across IIFEs in the codebase. With this, the rule not only enforces a style but also assists in the correction and standardization of existing and newly written code.
wrap-regex
Require parenthesis around regex literals
This ESLint rule is designed specifically to ensure readability and clarity when regular expressions (regex) are used in a chain of method calls. For example, it modifies /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.
The rule prevents potential confusion regarding the precedence of operations when a regex is involved in expressions. Since /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.
By enforcing regex literals to be wrapped in parentheses when used in member expressions, this rule aids in maintaining a consistent coding style across a codebase. This consistency can help new team members or contributors to understand the code faster and contribute more effectively.
The automated fixing feature of this rule, which adds the necessary parentheses around regex literals, simplifies code refactoring efforts. Developers do not have to manually search and wrap regex literals, saving time and reducing the risk of introducing syntax errors during manual code modifications.
yield-star-spacing
Require or disallow spacing around the *
in yield*
expressions
yield*
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
Require or disallow “Yoda” conditions
The rule specifically targets “Yoda” conditions, where the literal value is placed before the variable (e.g., 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.
It provides options to enforce or disallow Yoda conditions universally across the codebase, except in cases involving range checks or equality checks, where readability might not be significantly impaired. This flexibility allows teams to adapt the rule to their coding standards while still preventing inconsistency in condition formatting.
The rule includes functionality to automatically correct violations by flipping the sides of the expression to match the configured preference (either always enforcing Yoda conditions or always disallowing them). This auto-fixing feature facilitates codebase consistency without requiring manual intervention for each identified issue.
By considering exceptions for range tests and allowing configurations for only equality comparisons, the rule acknowledges that in some scenarios, Yoda conditions might enhance clarity or align with a team’s specific preferences. This nuanced approach ensures that the rule can be applied in a way that improves code quality and readability without being overly prescriptive.
accessor-pairs
Enforce getter and setter pairs in objects and classes
Enforces a consistent coding pattern that improves code readability and maintainability by ensuring that if a getter is defined for a property, a corresponding setter should also be defined, and vice versa. This reduces confusion for future developers who might expect to modify a property that only has a getter defined.
Helps in preventing unintentional read-only or write-only properties in objects and classes unless explicitly intended by the developer. This can be crucial in data encapsulation practices where the control over how a property’s value is set or retrieved needs to be closely managed.
The rule’s configurability allows teams to enforce the presence of getter-setter pairs according to their specific project requirements, such as checking for getter without setter or setter without getter, or even enforcing these rules for class members. This flexibility supports adherence to various coding standards and best practices across different types of projects.
Supports better design patterns in JavaScript programming by encouraging the use of getters and setters for controlling property access, which is a fundamental aspect of object-oriented programming. This can lead to more robust and secure code, as it allows for validation logic or side effects to be executed when properties are accessed or modified.
array-bracket-newline
Enforce linebreaks after opening and before closing array brackets
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
Enforce consistent spacing inside array brackets
This ESLint rule enforces a consistent spacing pattern inside array brackets, which directly impacts code readability and styling uniformity. This can be particularly beneficial in collaborative projects where maintaining a consistent coding style across multiple developers is crucial for project maintainability.
The rule provides an option to configure the desired spacing pattern either to always have spacing within array brackets or never have it. This allows teams to adapt the rule based on their coding standards and preferences, ensuring that the enforcement aligns with the team’s agreed-upon style guide.
The rule includes exceptions for single elements, objects within arrays, and arrays within arrays, which adds flexibility. This nuanced approach allows teams to enforce spacing rules while accommodating specific cases where a different spacing might be more readable or logical, ensuring the rule can be adapted to various coding scenarios without being overly rigid.
It automatically fixes spacing inconsistencies by adding or removing spaces as needed. This auto-fix feature significantly reduces the time and effort required for developers to comply with the spacing rules, allowing them to focus more on logic and less on formatting, ultimately speeding up the development process.
array-callback-return
Enforce return
statements in callbacks of array methods
This ESLint rule ensures all callbacks of array methods like .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.
The rule’s flexibility with options such as 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.
The inclusion of suggestions for fixes (like wrapping non-returning arrow functions in braces or prepending 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.
By checking the reachability of the last code path segment, the rule intelligently detects functions where not all paths return a value, further ensuring the reliability and predictability of the code. This promotes best practices in writing clean, error-free JavaScript code, especially in complex functions with multiple code paths.
array-element-newline
Enforce line breaks after each array element
multiline
, minItems
), allowing teams or projects to tailor the rule to match their coding style guidelines, thus maintaining codebase uniformity.arrow-body-style
Require braces around arrow function bodies
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
Require parentheses around arrow function arguments
arrow-spacing
Enforce consistent spacing before and after the arrow in arrow functions
const add = (a,b)=>a+b;
to the more readable const add = (a, b) => a + b;
.block-scoped-var
Enforce the use of variables within the scope they are defined
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
Disallow or enforce spaces inside of blocks after opening block and before closing block
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
Enforce consistent brace style for blocks
callback-return
Require return
statements after callbacks
camelcase
Enforce camelcase naming convention
This rule enforces a unified naming convention which improves the readability and consistency across the codebase by ensuring that variables, functions, and other identifiers are named in camelCase. This makes it easier for developers to understand the purpose and use of different entities within the code.
It includes exceptions through its options, such as allowing certain patterns or names (via the 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.
The rule is designed to avoid redundant reporting, particularly in the context of destructuring and shorthand notation, by using a Set to track reported nodes. This ensures that developers are not overwhelmed with duplicate warnings for the same issue, making the linting feedback more actionable and focused.
It supports backward compatibility options that prevent reporting in certain legacy scenarios, such as when identifiers are used in call expressions or as default values in destructuring or parameters. This consideration helps teams gradually adopt camelCase naming conventions without having to refactor existing codebases extensively before they can benefit from this rule.
capitalized-comments
Enforce or disallow capitalization of the first letter of a comment
class-methods-use-this
Enforce that class methods utilize 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
Require or disallow trailing commas
Ensures Consistency Across Codebases: By applying a specific style to trailing commas, whether it’s enforcing their presence or absence, the rule helps maintain a consistent code style across different parts of the project or even across different projects within an organization.
Eases Git Diffs: When trailing commas are enforced, adding new elements to objects or arrays doesn’t require modifying the line above to add a comma. This results in cleaner Git diffs where only the new lines are added, making code reviews more straightforward and minimizing merge conflicts.
Simplifies Array and Object Modification: By requiring trailing commas in multiline arrays and objects, developers can more easily add, remove, or reorder elements without having to worry about comma management, reducing the likelihood of syntax errors in modifications.
Adapts to Coding Standards with Flexibility: The rule is configurable to cater to different coding preferences and standards—‘always’, ‘never’, ‘always-multiline’, and ‘only-multiline’. This flexibility allows teams to adopt the convention that best suits their workflow and the readability of their code, whether they prefer a more traditional approach or one that leverages the benefits of trailing commas in modern JavaScript environments.
comma-spacing
Enforce consistent spacing before and after commas
comma-style
Enforce consistent comma style
This rule, when enforced, ensures a uniform comma style across various structures such as arrays, objects, functions, and more. Using it helps in maintaining a consistent code appearance, which can make the code easier to read and prevent errors related to irregular comma placements.
By offering customizable options and handling exceptions, the rule provides flexibility, allowing teams or projects to cater to specific stylistic preferences or requirements. This adaptability is crucial for aligning the linting rules with the project’s coding standards.
The rule includes fixer functions that automatically adjust the comma style to meet the specified guideline. This automated correction saves developers time during coding or code review processes, as they don’t have to manually fix each comma placement.
By targeting specific node types and their properties or elements (e.g., VariableDeclaration, ObjectExpression, ArrayPattern), the rule ensures that the comma style is enforced in both simple and complex language constructs. This thoroughness aids in catching inconsistencies that might be overlooked during manual reviews.
complexity
Enforce a maximum cyclomatic complexity allowed in a program
computed-property-spacing
Enforce consistent spacing inside computed property brackets
The rule ‘computed-property-spacing’ enforces a consistent spacing style inside computed property brackets, which can significantly improve code readability and maintainability by ensuring that all computed properties follow a single, consistent format. This helps developers to quickly understand the code, especially in large codebases where consistency is crucial for navigating and understanding different parts of the application.
It provides options to configure the spacing requirement as ‘always’ or ‘never’, giving teams the flexibility to tailor the rule to their coding standards. This adaptability ensures that the rule can support different stylistic preferences, making it applicable to various projects with distinct code style guidelines without forcing a one-size-fits-all approach.
The rule includes automated fixers that can automatically adjust spacing within computed properties to comply with the configured style. This feature saves time during code review and development by reducing manual linting efforts and helps maintain focus on more complex logic and application development tasks, rather than formatting.
By supporting automatic enforcement for class members when the ‘enforceForClassMembers’ option is enabled, it extends its utility beyond object properties to class member access expressions. This ensures that modern JavaScript classes and object-oriented approaches benefit from the same level of consistency and readability as traditional object notation, keeping the codebase modern and coherent.
consistent-return
Require return
statements to either always or never specify values
treatUndefinedAsUnspecified
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
Enforce consistent naming when capturing the current execution context
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
Require super()
calls in constructors
Enforces a key aspect of class inheritance in ES6 by requiring that super()
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.
This rule aids in detecting unreachable code segments where 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.
Helps maintain consistency and readability in codebases that utilize ES6 class syntax by enforcing a common pattern for constructor definitions in derived classes. This uniformity makes the code easier to read and understand, especially for developers who are new to a project.
By explicitly checking and reporting the use or omission of 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
Enforce consistent brace style for all control statements
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
Enforce default clauses in switch statements to be 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
Require default
cases in switch
statements
switch
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
Enforce default parameters to be last
The rule 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.
By enforcing default parameters to be at the end, it prevents potential errors when calling functions without specifying all arguments. Since JavaScript functions allow calling with fewer arguments than declared, having default parameters at the end ensures that the omitted arguments correctly map to those defaults, reducing the likelihood of unintended outcomes.
This rule aids in improving code readability and clarity. When a function with default parameters is called, it’s much clearer which arguments are optional and what their default values are. This clarity is especially beneficial for new team members or when revisiting old code, as it provides immediate context on how the function can be used without needing to refer back to its definition.
Implementing the 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
Enforce consistent newlines before and after dots
dot-notation
Enforce dot notation whenever possible
Improves readability: The enforcement of dot notation for property access enhances the readability of the code. It is generally easier and more straightforward to understand 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.
Encourages best practices: Dot notation is widely regarded as a best practice in JavaScript for accessing known and predictable property names. This rule aligns with such best practices, promoting code that is in harmony with common JavaScript idioms and patterns, thereby making it easier for developers to maintain and understand the code.
Automates code maintenance: Through its fix method, this rule offers automated code refactoring by replacing bracket notation with dot notation where applicable. This automation saves developer time and reduces the likelihood of manual errors during refactoring. It ensures that the codebase remains clean without requiring extensive effort from developers to adhere to this style guideline.
Configurability for exceptions: The rule provides options to allow for exceptions, such as when working with reserved keywords or when a certain pattern for property names is allowed that cannot be accessed with dot notation. This flexibility ensures that while the rule enforces a general best practice, it remains adaptable to specific coding requirements or styles, making it suitable for a wide range of projects without forcing unnecessary code changes.
eol-last
Require or disallow newline at the end of files
eqeqeq
Require the use of ===
and !==
This rule ensures that the code adheres to strict equality checks (===
and !==
), preventing unintended type coercion that can occur with abstract equality checks (==
and !=
). This enhances code reliability and predictability in comparisons.
By allowing configuration options such as “always”, “smart”, or considering 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.
The rule includes automatic fixing for cases where it’s safe to convert abstract equality into strict equality, specifically when comparing literals of the same type or in typeof
comparisons. This feature assists developers by reducing manual refactoring effort and accelerating the process of adopting strict equality checks.
Includes a specific check for 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
Enforce “for” loop update clause moving the counter in the right direction
This rule helps prevent infinite loops by ensuring that the counter in a “for” loop is moving in a direction that eventually meets the loop’s exit condition. For example, a counter that mistakenly decreases (i--
) when it should increase to reach a termination condition (i < 10
) could cause a loop to never terminate.
It specifically addresses and catches the misuse of update expressions (++
, --
) 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.
By checking if the update clause of the “for” loop correctly corresponds with the loop’s termination condition, this rule can help catch logical errors early in the development process. This contributes to more robust, error-free code by highlighting potential problems that are not always immediately evident through manual code reviews or testing.
It aids in maintaining code readability and understandability by enforcing a standard direction for counter updates in “for” loops. When the counter moves in the expected direction in relation to the loop’s completion condition, it aligns with most developers’ expectations and understanding of how “for” loops should operate, making the code easier to read and reason about.
func-call-spacing
Require or disallow spacing between function identifiers and their invocations
func-name-matching
Require function names to match the name of the variable or property to which they are assigned
Enforcing the use of this ESLint rule improves code readability and maintainability by ensuring that function names directly reflect their assignments. This makes it easier for developers to understand what a function does at a glance, particularly when navigating large codebases.
The rule aids in reducing developer confusion by preventing situations where a function’s name suggests a different functionality or scope than its actual implementation. By enforcing name matching, it becomes evident what role a function plays without needing to delve into its definition.
By including options to consider property descriptor patterns and CommonJS module exports, this rule is versatile enough to enforce consistent naming conventions across various coding paradigms and project structures. This adaptability makes it valuable for projects that incorporate multiple patterns for function declaration and exports.
The rule mitigates the risk of errors stemming from refactorings where a function’s name might change without updating its references or assignments, potentially leading to discrepancies that are difficult to debug. Enforcing matching names helps ensure that such updates are more atomic and self-contained, reducing the likelihood of introducing bugs during the refactoring process.
func-names
Require or disallow named function
expressions
This ESLint rule helps enforce a consistent naming convention for function expressions, which can improve readability and maintainability of the code. By requiring named function expressions, the rule helps ensure that stack traces are more informative, making debugging easier.
The rule allows for configuration to adapt to different project needs, including options to always require names, never require names, or require names only when needed (‘as-needed’). This flexibility allows teams to choose the most appropriate setting for their development practices, ensuring that the rule aligns with their specific code style guidelines.
It takes into account different contexts in which a function expression might not need a name, such as when the function name would be inferred in an ES6 environment. This reduces the likelihood of unnecessary warnings for functions that are implicitly named by their context, allowing developers to focus on more significant issues in their code.
The rule includes logic to skip checking for recursive functions by determining if the function’s name is being used within the function itself. This prevents false positives in scenarios where naming the function is necessary for recursion, ensuring that the rule does not discourage valid and necessary coding patterns.
func-style
Enforce the consistent use of either function
declarations or expressions
Consistency in codebase: This ESLint rule ensures that a project consistently uses either function declarations or function expressions (including the allowance of arrow functions if configured) throughout its entire codebase. Such consistency improves readability and reduces confusion for developers working on or entering the project.
Configurability for modern JavaScript syntax: The rule’s option to allow arrow functions while enforcing either function expressions or declarations gives projects the flexibility to adopt modern JavaScript practices in a controlled manner. This helps in maintaining the modernity of the codebase without compromising on the established code style guidelines.
Detects and enforces style at both declaration and usage: By checking not only the declaration but also the usage context of functions (e.g., whether they’re used in a variable declarator or as an export), this rule ensures that the function style adheres to the project’s guidelines in various scenarios, enhancing code consistency even in complex patterns.
Improves the ‘this’ keyword handling: The rule’s mechanism to track ThisExpression
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
Enforce line breaks between arguments of a function call
function-paren-newline
Enforce consistent line breaks inside function parentheses
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
Enforce consistent spacing around *
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
Enforce return
statements in getters
Ensures that getter functions, which are expected to return a value, fulfill their intended purpose by enforcing the inclusion of a return statement. This prevents silent failures or unexpected behavior in the program due to getters that perform actions but do not return a value.
Allows for the configuration flexibility to either mandate explicit returns in all getter functions or permit implicit returns, catering to different coding style preferences or project requirements while maintaining the rule’s core objective.
Enhances code readability and maintainability by promoting a consistent structure within getter functions, making them easier to understand at a glance. This consistency helps new developers or contributors to quickly grasp the purpose and behavior of getters in the codebase.
Helps in identifying unreachable or dead code segments within getter functions, thereby aiding in debugging and optimizing the code by removing or refactoring parts that do not contribute to the expected output of the getter.
global-require
Require require()
calls to be placed at top-level module scope
require()
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
Require grouped accessor pairs in object literals and classes
guard-for-in
Require for-in
loops to include an if
statement
This rule ensures that the for-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.
By enforcing an 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.
The rule helps maintain consistency across the codebase by establishing a specific pattern for iterating over object properties. This can aid in code readability and maintainability, as developers can quickly understand the intended logic without needing to guess whether the loop was supposed to iterate over own properties or include inherited ones as well.
It implicitly encourages developers to think about the implications of iterating over properties, potentially leading to a deeper understanding of JavaScript’s prototypal inheritance and the differences between enumerating over an object’s own properties compared to all enumerable properties found along its prototype chain.
handle-callback-err
Require error handling in callbacks
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
Disallow specified identifiers
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
Disallow specified identifiers
id-length
Enforce minimum and maximum identifier lengths
id-match
Require identifiers to match a specified regular expression
implicit-arrow-linebreak
Enforce the location of arrow function bodies
indent-legacy
Enforce consistent indentation
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
Enforce consistent indentation
index
init-declarations
Require or disallow initialization in variable 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
Enforce the consistent use of either double or single quotes in JSX attributes
This rule enforces consistency in quotes usage within JSX attributes which can improve readability and maintainability of the code by establishing a uniform coding style. Consistency in coding practices is especially crucial in projects with multiple developers to avoid unnecessary stylistic changes in code reviews.
By providing an automatic fix option, it reduces the workload on developers and minimizes the potential for human error when manually replacing quotes to adhere to the project’s style guidelines. This automation feature enhances developer productivity and focus by allowing them to concentrate on more critical issues in the code.
The rule helps prevent potential bugs related to the incorrect usage of quotes in JSX attributes. While JSX syntax closely resembles HTML, it has distinct differences that could lead to errors if not properly handled; consistent quote usage as enforced by this rule aids in mitigating such risks.
It supports configurability to prefer either double or single quotes, thus allowing teams to align the rule with their existing coding standards or personal preferences without enforcing a one-size-fits-all approach. This flexibility is vital for adopting the rule across a variety of projects with different stylistic guidelines.
key-spacing
Enforce consistent spacing between keys and values in object literal properties
This rule ensures consistency in the way keys and values are spaced within object literals, making the code easier to read and maintain. By dictating whether spaces should exist before or after the colon, it eliminates variations in style that can cause unnecessary focus on formatting during code reviews.
The rule offers a level of customization for alignment options, allowing teams to enforce either a vertical alignment based on the colon or the value. This flexibility lets teams adhere to a coding standard that best matches their readability preferences and existing coding styles.
By providing auto-fix capabilities, this rule not only highlights inconsistencies but also simplifies the process of correcting them. Developers can automatically adjust spacing around colons in object literals without manually altering each instance, speeding up both the development and the code review process.
The rule’s ability to form groups of properties and check for vertical alignment within those groups helps maintain a clean, organized structure in object literals. This organizational aspect is particularly beneficial in large objects where maintaining readability can become challenging, ensuring that related properties are styled in a cohesive manner.
keyword-spacing
Enforce consistent spacing before and after keywords
line-comment-position
Enforce position of line comments
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
Enforce consistent 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
Require empty lines around comments
The rule ensures that comments are adequately separated from surrounding code, thereby improving readability and making the code easier to understand for all developers, especially those who may be new to the project.
By enforcing empty lines around comments, this rule helps in visually distinguishing the comments from the code blocks, making it easier to identify comment sections at a glance without them getting lost in the code.
The rule accommodates various programming constructs, like classes, blocks, and arrays, by providing specific options to either allow or disallow empty lines around comments in these contexts, offering flexibility to adhere to different coding standards or preferences.
It provides functionality to ignore specific patterns within comments, allowing developers to specify exceptions to the rule. This is particularly useful for auto-generated comments or code regions where the usual empty line requirement around comments might not be desirable or necessary.
lines-around-directive
Require or disallow newlines around directives
lines-between-class-members
Require or disallow an empty line between class members
logical-assignment-operators
Require or disallow logical assignment operator shorthand
Enhances code readability by using shorthand logical assignment operators (e.g., ||=
, ??=
) 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.
Helps to reduce the risk of typos or logical errors that can occur when manually typing out the longer form of these logical assignments (e.g., 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.
Encourages consistency across codebases by enforcing a specific style for logical assignments. Whether the chosen mode is “always” use shorthand or “never” use shorthand, adhering to one style helps maintain uniformity, making the code easier to follow and maintain by different developers or teams.
Offers conditional fixes and suggestions that are context-aware (e.g., avoiding changes that would alter the meaning of the code if the target of the assignment could be a getter, or if comments are present within the expression). This careful approach ensures that automated code fixes introduced by ESLint do not unintentionally introduce side effects or change the program’s behavior, particularly in nuanced situations like mixing ??
with ||
/&&
, or when dealing with potentially problematic code constructs such as with statements or strict mode considerations.
max-classes-per-file
Enforce a maximum number of classes per file
Encourages single responsibility principle: By enforcing a maximum number of classes per file, this rule directly encourages developers to adhere to the single responsibility principle. It ensures that each class is focused on a specific functionality, improving code readability and maintainability.
Facilitates easier code navigation: When there is only one class per file, it becomes significantly easier for developers to locate and navigate to the code they need to work on. This is especially beneficial in larger projects where searching for specific classes could otherwise become cumbersome.
Enhances code clarity: Limiting the number of classes per file reduces clutter and makes the file’s purpose and functionality clearer to anyone reading the code. This can be particularly helpful for new team members trying to familiarize themselves with a project, as understanding the structure and responsibilities of classes becomes straightforward.
Improves refactoring and testing: With only a single class per file, refactoring code and writing tests become simpler and less error-prone. Developers can easily identify which files need to be updated when a class changes, and unit tests can be more clearly associated with the class being tested. This can lead to better testing practices and a more stable codebase overall.
max-depth
Enforce a maximum depth that blocks can be nested
max-len
Enforce a maximum line length
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
Enforce a maximum number of lines of code in a function
max-lines
Enforce a maximum number of lines per file
max-nested-callbacks
Enforce a maximum depth that callbacks can be nested
max-params
Enforce a maximum number of parameters in function definitions
max-statements-per-line
Enforce a maximum number of statements allowed per line
max-statements
Enforce a maximum number of statements allowed in function blocks
multiline-comment-style
Enforce a particular style for multiline comments
multiline-ternary
Enforce newlines between operands of ternary expressions
Improves Code Readability: Applying this rule forces a consistent structure in multiline ternary expressions, which inherently makes complex logic easier to read and understand. When each operand is on its separate line, it becomes clearer what the condition, true case, and false case are, reducing cognitive load when scanning code.
Enhances Maintainability: With standardized formatting, future modifications to any part of the ternary expression become simpler. Developers can easily insert or remove conditions or outcomes without disturbing the overall layout of the code block, ensuring that updates do not introduce formatting inconsistencies.
Minimizes Merge Conflicts: In collaborative environments, consistent code formatting, especially for conditional logic, can reduce the occurrence of merge conflicts. Since this rule enforces a specific structure, it’s less likely that different formatting preferences among team members will lead to conflicts in version control systems.
Facilitates Automated Tooling: The rule’s design allows for automatic enforcement and fixing of formatting issues related to multiline ternary expressions. This not only saves time during code reviews by reducing manual nitpicking over style but also allows integration with continuous integration/continuous deployment (CI/CD) pipelines to ensure code style consistency across the codebase without human intervention.
new-cap
Require constructor names to begin with a capital letter
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
Enforce or disallow parentheses when invoking a constructor with no arguments
newline-after-var
Require or disallow an empty line after variable declarations
newline-before-return
Require an empty line before return
statements
return
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
Require a newline after each call in a method chain
ignoreChainWithDepth
option to meet their specific needs, tailoring the rule enforcement to match preferred coding guidelines.no-alert
Disallow the use of alert
, confirm
, and prompt
Improves user experience: Usage of methods like 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.
Enhances application security: Historically, these dialog methods have been prone to misuse, such as phishing attempts through spoofed dialogs. By disallowing these methods, the rule indirectly contributes to mitigating certain types of security risks.
Promotes modern web standards: The shift away from 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.
Facilitates better debugging and logging practices: Replacing methods like 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
Disallow Array
constructors
This rule enforces the use of more readable and concise syntax for creating arrays, such as using array literals ([]
) instead of the Array
constructor. This makes the code easier to understand, especially for those new to JavaScript or coming from other programming languages.
It helps prevent potential confusion or errors when using the 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.
The rule includes a fix suggestion mechanism that not only identifies the less preferred usage but also provides developers with an immediate suggestion on how to rectify it. This can improve development efficiency by reducing the time spent on manual code reviews for such patterns.
By enforcing a uniform way of creating arrays across the codebase, it can enhance code consistency and quality. When developers follow a standardized approach, it reduces the cognitive load required to understand different sections of the code, leading to a more maintainable and scalable codebase.
no-async-promise-executor
Disallow using an async function as a Promise executor
Prevents the common anti-pattern of using an async function as a Promise executor, which can lead to unhandled promise rejections. This specifically addresses issues where exceptions thrown in the async executor function are not properly caught by the surrounding code, leading to potential debugging challenges and runtime errors that are harder to track down.
Promotes the use of more standard and predictable patterns for creating new Promises. By disallowing async functions within the executor, it encourages the use of then/catch chaining or the async/await syntax outside of the executor function, which aligns with more conventional JavaScript promise handling practices.
Enhances code readability and maintainability by steering developers away from a pattern that might seem convenient but actually introduces complexity. The rationale behind this rule directly targets reducing the cognitive load for developers by advocating for more straightforward and universally understood promise creation and handling patterns.
Increases the robustness of error handling in asynchronous operations. The rule ensures that errors are explicitly handled through reject or caught in a catch block, rather than potentially disappearing into the void due to the quirks of async functions as promise executors. This is particularly important in environments where reliability and error transparency are crucial.
no-await-in-loop
Disallow await
inside of loops
The rule no-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.
By disallowing 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.
It helps in spotting unintentional serial execution of what could be parallel tasks. Developers might not always realize that using 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.
This rule can lead to the adoption of better coding practices by enforcing the consideration of alternative approaches to achieving the same goal without compromising on performance. For example, refactoring code to use 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
Disallow bitwise operators
This rule specifically helps in maintaining code readability and understandability. Bitwise operators can be obscure to some developers, especially those not familiar with low-level programming concepts, and using more descriptive methods or operations can improve the clarity of what the code is intended to do.
By discouraging the use of bitwise operators, this rule fosters writing code that is less prone to subtle bugs. It’s easy to misuse bitwise operators or misunderstand their effects, especially in high-level programming tasks, leading to errors that are difficult to diagnose.
The rule implicitly encourages the use of JavaScript’s standard library functions (e.g., 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.
It allows for exceptions through its configuration options, making it adaptable for cases where bitwise operations are justified or necessary, such as performance-sensitive code or when interfacing with binary data. This ensures that developers are not overly restricted where there is a valid use case for these operators.
no-buffer-constructor
Disallow use of the Buffer()
constructor
The rule targets the prevention of using the deprecated Buffer()
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.
It encourages using safer alternatives like 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.
Enforcing this rule assists in future-proofing the codebase, considering Node.js has officially deprecated the use of the old 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.
The rule not only identifies the deprecated usage but also suggests modern, safer alternatives which can lead to both faster execution times (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
Disallow the use of 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
Disallow lexical declarations in case clauses
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
Disallow catch
clause parameters from shadowing variables in the outer scope
Prevents confusion and improves code readability by ensuring that catch clause parameters have unique names, avoiding confusion with variables in the outer scope. This is particularly important in complex try-catch structures where shadowing could lead to misunderstanding which variable is being referenced.
Enhances debuggability by ensuring the integrity of variable values in the outer scope. If a catch clause inadvertently shadows an outer scope variable, during debugging, it might appear that the outer scope variable’s value is changing, when in fact, it’s the catch clause’s parameter that is being altered.
Contributes to cleaner code maintenance and refactoring by explicitly disallowing shadowing in catch clauses, thus preventing potential bugs that might arise in the future when the code is modified or extended. This rule forces developers to choose unique names, leading to a more thoughtful naming strategy and potentially more descriptive variable names.
Supports good programming practices in languages like JavaScript where scopes can be easily misunderstood or overlooked. By ensuring that catch parameters do not shadow outer variables, it indirectly educates developers about scope management and encourages practices that make the code more predictable and easier to understand for new developers or during code reviews.
no-class-assign
Disallow reassigning class members
no-compare-neg-zero
Disallow comparing against -0
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
Disallow assignment operators in conditional expressions
This rule helps prevent accidental assignments in conditional expressions, which are a common source of bugs. For example, using =
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.
By enforcing this rule, developers are encouraged to write clearer and more intentional conditional logic. The requirement to enclose assignments within parentheses if they are to be used in a conditional expression makes the developer’s intent explicit, both to the JavaScript engine and to anyone reading the code.
The rule supports a configurable option ("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.
It improves code readability and maintainability by ensuring that conditional expressions are straightforward and easy to understand at a glance. By disallowing assignments in conditionals or requiring them to be explicitly wrapped in parentheses, the codebase becomes more uniform and less prone to errors, making it easier for new developers to understand the code and for teams to maintain it over time.
no-confusing-arrow
Disallow arrow functions where they could be confused with comparisons
The rule prevents the confusion between arrow functions and comparison operators in code. For instance, 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.
By offering the option to require parentheses around the function body when using conditional expressions, it enforces a clearer syntax, making it immediately obvious that the expression is intended to be the return value of the arrow function, not a comparison. This leads to cleaner and more understandable code, especially for those who may be newer to JavaScript or coming from a different programming background.
The configurable options 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.
The rule helps in automated code refactoring and consistency across a codebase by providing a fix mechanism that can automatically adjust arrow functions to include parentheses where necessary. This reduces manual effort in code review and maintenance, ensuring that all arrow functions conform to the team’s style guide with minimal developer intervention.
no-console
Disallow the use of 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
Disallow reassigning const
variables
const
, 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
Disallow expressions where the operation doesn’t affect the value
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
Disallow constant expressions in conditions
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
Disallow returning value from constructor
This rule helps enforce the standard JavaScript behavior where constructors implicitly return the newly created object, ensuring consistency across your codebase. By disallowing explicit returns, it prevents confusion among developers about what a constructor is supposed to do, which is to initialize the object, not to decide what to return.
It prevents potential errors in object creation, as returning anything other than the current instance (this) from a constructor will replace the instance one might expect to receive. This is particularly important in cases where an explicit return might inadvertently return the wrong value or type, leading to bugs that are difficult to trace.
The rule encourages the use of proper error handling within constructors by blocking return statements. This pushes developers to use exceptions for error signaling in constructors (e.g., using throw
for invalid input values) instead of returning null or any other value, thereby promoting a more robust error handling strategy.
Ensuring that constructors do not return values helps in maintaining clarity and readability of the code. It makes the behavior of constructors predictable, as they solely focus on instance initialization. This rule, therefore, aids in enforcing a coding standard that aligns with the expectations of JavaScript’s object-oriented design principles.
no-continue
Disallow continue
statements
The no-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
.
It promotes the practice of handling conditions explicitly within the loop’s logic itself, rather than skipping iterations. This explicitness can lead to more readable and maintainable code, as the conditions for proceeding with the loop’s body are directly tied to the logic within the loop, rather than being negated and skipped.
By disallowing the use of 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.
The rule fosters the development of alternative solutions that may have performance benefits. In certain cases, redesigning loop logic to avoid 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
Disallow control characters in regular expressions
no-debugger
Disallow the use of 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
Disallow deleting variables
Enforces a better understanding of variable deletion and its effects in JavaScript, specifically preventing developers from attempting to delete variables which is not a valid operation in JavaScript. This helps maintain the integrity of the execution environment by avoiding errors at runtime due to improper deletion attempts.
Encourages the use of proper techniques for removing or clearing data. For instance, setting a variable to 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.
This rule highlights the correct usage of the 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.
Prevents potential memory leaks and ensures cleaner, more predictable code. By disallowing the deletion of variables, which JavaScript does not support as expected, developers are guided towards practices that do not lead to unintended side effects or the misuse of language features.
no-div-regex
Disallow equal signs explicitly at the beginning of regular expressions
/=
) 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
Disallow duplicate arguments in function
definitions
no-dupe-class-members
Disallow duplicate class members
no-dupe-else-if
Disallow duplicate conditions in if-else-if chains
no-dupe-keys
Disallow duplicate keys in object literals
no-duplicate-case
Disallow duplicate case labels
no-duplicate-imports
Disallow duplicate module imports
no-else-return
Disallow else
blocks after return
statements in if
statements
Improves Readability: Using the no-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.
Reduces Code Complexity: By enforcing the removal of unnecessary 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.
Promotes Early Exit Pattern: The rule implicitly promotes the use of the early exit (or guard clause) pattern, where conditions that lead to terminating the function are handled at the beginning, and the main body of the function follows without being nested within else
blocks. This pattern can enhance the function’s clarity and maintainability.
Avoidance of Unintentional Scope Leaks: Since this rule encourages refactoring code to eliminate unnecessary 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
Disallow empty character classes in regular expressions
This rule helps in identifying and preventing syntax errors in regular expressions that can lead to unexpected matches or no matches at all. An empty character class, as indicated in the “bad” example, does not match any character and could be a developer’s oversight.
It enhances the readability and maintainability of the code by ensuring that all character classes in regular expressions are explicitly defined. This makes the regular expressions more understandable to new developers or others revisiting the code.
By disallowing empty character classes, it aids in avoiding potentially costly runtime errors or inefficient execution of regular expressions, as the JavaScript engine might spend time evaluating an expression that logically cannot match any character.
The rule indirectly educates developers about correct regular expression syntax and practices by pointing out a common mistake. This educational aspect can improve overall code quality and developer skill in writing more effective and error-free regular expressions.
no-empty-function
Disallow empty functions
This ESLint rule specifically targets empty functions across different syntaxes, including traditional function declarations, function expressions, and arrow functions, ensuring a uniform enforcement throughout the codebase. It helps in maintaining code quality by disallowing functions that do nothing, which can be confusing or misleading to developers, thereby promoting the use of meaningful, action-oriented functions.
The rule allows for customization through options, enabling teams to specify exceptions where an empty function might be permissible according to their project needs. This flexibility ensures that teams can adapt the rule to fit specific scenarios, such as stubbing out functions for future implementation or when using lifecycle methods in frameworks that don’t require an implementation body.
By checking for the absence of both code and comments within the body of the function, the rule encourages developers to either implement the function or provide explanatory comments about why the function is intentionally left empty. This practice improves code readability and maintainability, making it easier for others to understand the purpose of empty functions or the intention behind leaving them as placeholders.
Implementing this rule and adhering to its guidance can help in reducing potential bugs in the software development process. Empty functions can sometimes be a result of incomplete refactoring or placeholders forgotten by developers. By flagging these instances, the rule assists in preemptively identifying areas of the code that may require further attention or completion, thus contributing to a more robust development cycle.
no-empty-pattern
Disallow empty destructuring patterns
The rule helps prevent the use of empty destructuring patterns that can lead to confusion or suggest an incomplete implementation. When developers see an empty pattern, they might wonder if it’s intentional or a mistake, leading to unnecessary code review comments or assumptions.
By disallowing empty destructuring patterns, this rule enforces more deliberate code writing practices. Developers are encouraged to clearly state their intentions, making code easier to understand. For example, if one intends to use variables from an object or array, they should explicitly list them, improving code readability and intention clarity.
The rule offers configurability with the 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.
It directly addresses potential performance concerns by encouraging the removal of unnecessary operations. Destructuring with empty patterns could lead to unnecessary work, such as copying properties or elements that are never used. By enforcing the use of non-empty patterns, it ensures that every destructuring operation has a clear purpose, contributing to more efficient code.
no-empty-static-block
Disallow empty static blocks
no-empty
Disallow empty block statements
This rule helps maintain code clarity by ensuring that block statements, which inherently imply the execution of statements, are not misleadingly left empty without explanation. It prevents developers from creating blocks of code that do nothing, thereby avoiding confusion for future maintenance or review by other developers.
It makes an exception for specific scenarios like allowing empty catch blocks if configured (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.
The rule supports code readability and documentation by suggesting the inclusion of comments within empty blocks. This encourages developers to explicitly state the rationale behind leaving a block empty, thereby not leaving room for speculation about whether the empty block is a mistake or intentional.
It emphasizes good coding practices by also covering switch statements with no cases, encouraging developers to refactor their code for better readability and maintainability. This ensures that switch statements serve their purpose of handling multiple cases and are not misused or left incomplete.
no-eq-null
Disallow 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
Disallow the use of 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
Disallow reassigning exceptions in catch
clauses
catch
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
Disallow extending native types
no-extra-bind
Disallow unnecessary calls to .bind()
The rule helps ensure that .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.
By disallowing unnecessary .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
.
It encourages developers to understand and correctly use the scope and context (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.
It incorporates automated fixing for violations, which not only helps in educating developers about unnecessary .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
Disallow unnecessary boolean casts
!!
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
Disallow unnecessary labels
The ‘no-extra-label’ rule helps in maintaining code clarity by disallowing unnecessary labels that could otherwise clutter the code and make it harder to read. Labels that are not needed for the logical flow of the program are identified and removed, making the code more straightforward for other developers to understand.
It aids in the optimization of JavaScript execution. While modern JavaScript engines are highly optimized, unnecessary labels can still introduce a minor overhead in parsing. By removing these unnecessary labels, the rule ensures that the JavaScript code is as lean and efficient as possible.
This rule prevents potential errors in large codebases where labels might be reused inappropriately or might lead to confusion regarding the scope of breaks and continues. By ensuring that only necessary labels are used, it reduces the possibility of control flow errors that can be hard to debug.
It promotes best practices in coding by encouraging developers to use control structures in a clear and logical manner without relying on unnecessary labeled statements. This can be particularly helpful for new developers learning to write clean code and for maintaining a high quality of code in collaborative projects where consistency is key to readability and maintainability.
no-extra-parens
Disallow unnecessary parentheses
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
Disallow unnecessary semicolons
It eliminates syntax redundancy by removing unnecessary semicolons, which can improve code readability and maintain a cleaner codebase. Specifically, it targets semicolons that do not contribute to the code’s functionality, as demonstrated in the examples where semicolons after function declarations and for loops are identified as superfluous.
The rule includes logic to determine if a semicolon is fixable, considering nuanced cases where removal of a semicolon could change the meaning of subsequent strings into directives. This careful consideration ensures that the fix applied does not inadvertently alter the program’s correct behavior, making automation both safer and more reliable.
By reporting unnecessary semicolons within class bodies and after method definitions explicitly, it aids in enforcing coding style consistency specifically in object-oriented structures. This is crucial as the complexity of class definitions might lead to more frequent stylistic inconsistencies, making focused rules like this valuable for maintaining uniformity.
It provides an automated fixing mechanism that is context-aware, meaning it only suggests or implements fixes where the removal of the semicolon would not lead to syntax errors or misunderstood expressions. This automation supports faster code refactoring, allowing developers to focus on more complex problems instead of manually fixing stylistic issues.
no-fallthrough
Disallow fallthrough of case
statements
This rule helps in maintaining the integrity of switch
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.
The rule can improve code readability and maintainability. For developers reading the code, it becomes immediately clear whether the fallthrough is intentional or not. If the fallthrough is intentional, the expectation is that it will be accompanied by a comment explaining why. This makes the code easier to understand and maintain over time.
It allows for some flexibility through configuration options, such as 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.
By checking for comments that explain intentional fallthroughs and allowing configuration of the comment pattern, this rule encourages developers to document their code better. This not only improves the immediate understandability of the code but also helps in long-term maintenance as future developers can understand the reasoning behind certain coding decisions.
no-floating-decimal
Disallow leading or trailing decimal points in numeric literals
.5
is transformed into 0.5
, and 123.
is transformed into 123.0
.no-func-assign
Disallow reassigning function
declarations
Prevents confusion and potential bugs that can occur when a function declaration is reassigned. For instance, if a developer accidentally reassigns a function, it could lead to unexpected behavior or runtime errors.
Maintains function declaration immutability within the codebase, ensuring that declared functions remain constant throughout the lifecycle of the application. This immutability concept is especially important in larger projects where tracking function behavior is critical.
Enhances code readability and maintainability by enforcing a clear and consistent structure for function usage. When functions are not reassigned, their behavior is easier to predict, making the code easier to understand and debug.
Aids in static analysis by enabling tools like ESLint to more accurately understand and predict the code’s behavior, since the reassignment of functions can complicate the control flow and scope resolution, leading to less precise analysis outcomes.
no-global-assign
Disallow assignments to native objects or read-only global variables
no-implicit-coercion
Disallow shorthand type conversions
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
Disallow declarations in the global scope
no-implied-eval
Disallow the use of eval()
-like methods
eval()
-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
Disallow assigning to imported bindings
This ESLint rule prevents accidental or intentional alterations to imported bindings, ensuring that module interfaces remain consistent and predictable across different parts of the application. Modifying imported bindings can lead to subtle bugs and unexpected behavior as it goes against the design of ES6 module semantics, where imports are read-only.
The rule aids in code maintainability and readability by enforcing clearer distinctions between locally declared variables and imported bindings. When developers are prevented from assigning to imported bindings, they are encouraged to use more straightforward and understandable patterns for managing state and dependencies.
It supports the principle of immutability for imported modules, which can lead to safer code. Immutable data patterns are easier to reason about and debug. By enforcing this rule, developers are nudged towards adopting these beneficial practices, leading to fewer side effects and unpredictable state changes in the codebase.
The rule is particularly useful in large codebases or in projects with multiple contributors, where tracking the origin and flow of data can become challenging. By ensuring that imported bindings remain unchanged, it simplifies the task of understanding how data flows through the application and how different modules interact with each other. This can significantly reduce the time required for new developers to familiarize themselves with the codebase and for existing developers to track down bugs or implement new features.
no-inline-comments
Disallow inline comments after code
Promotes readability by enforcing a clear separation between code and comments, ensuring that comments do not clutter the side of the code. This separation can make the code easier to read, especially for complex logic where inline comments might disrupt the flow of understanding.
Helps maintain a consistent code commenting style across a project, which can be particularly beneficial in team environments where multiple developers contribute to the codebase. Consistency in how comments are made improves the overall code quality and collaboration.
Increases the chance that comments will be more thoughtful and explanatory rather than just being quick annotations that might not fully explain the reasoning behind the code. When developers are encouraged to place comments above the line of code, they may take a moment to provide more context or clarification.
Avoids potential issues with language syntaxes or tooling that might misinterpret inline comments, especially in complex scenarios involving multiple languages or preprocessors where inline comments could inadvertently affect the execution or processing of code.
no-inner-declarations
Disallow variable or function
declarations in nested blocks
no-invalid-regexp
Disallow invalid regular expression strings in RegExp
constructors
u
and v
), thus aligning with ECMAScript specifications and ensuring broader compatibility and predictability of regex behavior across different JavaScript engines.no-invalid-this
Disallow use of 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
Disallow irregular whitespace
This ESLint rule is specifically tailored to identify and report irregular whitespace characters that can cause issues in code readability, and potentially lead to problematic bugs that are hard to spot during code review. By automating the detection of such characters, this rule ensures that all whitespace in the codebase follows a consistent pattern, which is a crucial aspect for maintaining high code quality.
The rule provides configurable options to skip certain areas where irregular whitespace might be intentionally used or where its presence doesn’t impact the execution or readability of code, such as comments, strings, regular expressions, template literals, and JSX text. This level of granularity allows teams to apply strict whitespace conventions without disrupting workflows where exceptions to the rule are justified, thereby balancing code quality with practical coding scenarios.
By filtering out irregular whitespace in literals, regular expressions, templates, and JSX text based on developer preferences, this rule not only enhances the readability and consistency of code but also respects the context-specific needs of different types of code constructs. This ensures that automatic linting does not interfere with intentional design or formatting decisions that may rely on specific whitespace characters in these contexts.
The rule contributes to the overall maintainability and readability of the codebase by enforcing a standardized approach to handling whitespaces. Regular spacing is easier to read, understand, and debug, especially for teams working in collaborative settings or when the code is handed off to new developers. Consistency in code formatting, including whitespace usage, is a key aspect of code quality that can significantly impact developer productivity and the long-term sustainability of a project.
no-iterator
Disallow the use of the __iterator__
property
This ESLint rule specifically targets and disallows the use of the non-standard __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.
Implementing this rule helps in avoiding potential runtime errors or unexpected behavior in browsers or environments that do not support the __iterator__
property, thereby improving the reliability of the code.
By disallowing the __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.
Enforcing this rule can aid in codebase modernization efforts, by identifying and discouraging outdated and non-standard practices. As the JavaScript language evolves, adopting standard and future-proof iteration methods over proprietary or deprecated ones is beneficial for long-term code health and interoperability.
no-label-var
Disallow labels that share a name with a variable
no-labels
Disallow labeled statements
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
Disallow unnecessary nested blocks
let
and const
declarations within unnecessary blocks, which might behave differently than the developer expects if misunderstood.no-lonely-if
Disallow if
statements as the only statement in else
blocks
if
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
Disallow function declarations that contain unsafe references inside loop statements
Ensures that functions defined within loops do not inadvertently reference loop variables from an outer scope, which can lead to bugs, especially with asynchronous code. This prevents unexpected behaviors by ensuring variables are properly scoped.
Improves code maintainability by encouraging the use of patterns that make the scope and lifetime of variables clear, reducing the cognitive load on developers trying to understand the flow of variables within loops.
Helps to identify instances where variables may change value before a function is executed, particularly relevant in asynchronous operations like setTimeout
, mitigating issues related to closures capturing loop variables.
Encourages best practices in JavaScript development by highlighting a common mistake, enhancing code quality, and potentially leading to performance improvements by avoiding unnecessary closures within loops.
no-loss-of-precision
Disallow literal numbers that lose precision
no-magic-numbers
Disallow 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
Disallow characters which are made with multiple code points in character class syntax
The rule helps to identify characters in regular expressions that are made with multiple code points and might not be interpreted correctly without the proper flags, specifically the Unicode u
flag. This ensures that developers do not unintentionally write regular expressions that fail to match intended characters.
It automatically suggests a fix by adding the 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.
By enforcing the use of the 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.
The rule educates developers about the importance of correctly handling Unicode characters in JavaScript, which might otherwise be overlooked. It brings attention to an aspect of JavaScript and regular expression syntax that is crucial for internationalization and working with modern web applications that handle diverse character sets.
no-mixed-operators
Disallow mixed binary operators
5 + 10 * 3 - 2
could confuse readers about the sequence of operations.(5 + (10 * 3)) - 2
.no-mixed-requires
Disallow require
calls to be mixed with regular variable declarations
The rule enforces a clean and organized code structure by avoiding the mixture of require
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.
By allowing options like 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.
It indirectly promotes the use of modern JavaScript practices by highlighting the separation and explicit declaration of dependencies at the top of the file or function scope. While not preventing the use of 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.
The rule comes with a built-in logic to distinguish between different types of 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
Disallow mixed spaces and tabs for indentation
no-multi-assign
Disallow use of chained assignment expressions
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
Disallow multiple spaces
no-multi-str
Disallow multiline strings
Ensures code consistency and readability: Multiline strings using backslashes can be confusing and less readable, especially for developers new to the codebase or those not familiar with this particular JavaScript syntax. Enforcing a standard for multiline strings helps maintain code consistency and improves readability, making it easier for team members to read and understand code quickly.
Helps avoid runtime errors: Multiline strings defined with backslashes might lead to hard-to-detect errors in the code, especially if a developer accidentally removes or mismatches a backslash. By disallowing multiline strings in this manner, this rule helps preempt potential runtime errors that could be caused by such mistakes, contributing to the overall stability of the application.
Encourages the use of template literals or concatenation: By disallowing multiline strings, developers are encouraged to use template literals or string concatenation instead. These alternatives are part of modern JavaScript and offer clearer syntax and functionality for defining multiline strings, including variable interpolation in the case of template literals, which can lead to more expressively written code.
Adapts to JSX considerations: The rule is designed with exceptions for JSX elements, acknowledging the unique syntax and requirements of JSX when it comes to dealing with strings. This nuance ensures that the rule doesn’t inadvertently enforce a restriction in contexts where multiline strings might be necessary or more common, such as within JSX elements, allowing developers to write JSX code efficiently without compromising on the specific needs of UI development within React or other JSX-utilizing libraries.
no-multiple-empty-lines
Disallow multiple empty lines
no-native-reassign
Disallow assignments to native objects or read-only global variables
window
or undefined
, which could lead to severe implications for the application’s functionality.no-negated-condition
Disallow negated conditions
no-negated-in-lhs
Disallow negating the left operand in in
expressions
Prevents confusion when reading code that checks for the non-existence of a property within an object. Since !'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.
Enhances code readability and clarity by ensuring the negation applies to the entire operation rather than just to the left operand. The correct pattern !('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.
Helps in maintaining consistency across the codebase by enforcing a pattern for negating conditions which involve the in
operator. This reduces the likelihood of mistakes that could arise from developers using different patterns for similar checks.
Could potentially prevent subtle bugs related to precedence. In JavaScript, the 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
Disallow nested ternary expressions
Prevents decreased readability: Nested ternary operators, especially when they span multiple lines or are part of complex expressions, can significantly decrease code readability. This rule ensures that each conditional logic is clear and straightforward, making the code easier for developers to read and understand.
Facilitates easier debugging: Debugging issues within nested ternary operations can be challenging due to the condensed way in which the conditionals are presented. By disallowing nested ternaries, this rule promotes structuring conditionals in a way that can be more easily stepped through with a debugger.
Encourages better maintainability: Code that is easier to read and understand is naturally easier to maintain. With the disallowance of nested ternary expressions, developers are encouraged to write more maintainable code by using clearer alternatives like if-else statements, which can be quickly adjusted or extended without the complexity of untangling nested conditionals.
Enhances team collaboration: In team environments, code consistency and clarity are paramount. By enforcing a rule against nested ternary expressions, the team adopts a uniform approach to writing conditional logic. This alignment helps prevent misunderstandings or the need for rewrites when code passes between team members, ultimately improving collaboration and efficiency.
no-new-func
Disallow new
operators with the Function
object
Function
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
Disallow new
operators with global non-constructor functions
new
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
Disallow 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
Disallow new
operators with calls to require
This rule specifically targets the prevention of using the 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.
Enforcing this rule ensures that modules are loaded as intended by their authors. Using 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.
Application performance can be indirectly affected. Instantiating a required module with 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.
It promotes code readability and maintainability. By adhering to a common pattern for module importation (i.e., using 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
Disallow new
operators with the Symbol
object
Ensures compliance with ECMAScript specification: The JavaScript specification defines the Symbol
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.
Prevents runtime exceptions: Utilizing 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.
Educates developers: For developers unfamiliar with the unique nature of 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.
Maintains consistency in codebase: By enforcing the creation of symbols using 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
Disallow 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
Disallow new
operators outside of assignments or comparisons
new
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
Disallow \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
Disallow calling global object properties as functions
This rule directly targets a common misunderstanding among JavaScript developers where global objects like 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.
It enhances code readability and maintainability by ensuring that global objects are used correctly according to their intended purpose. For instance, distinguishing between correct (Math.round(5.76)
) and incorrect (Math(5.76)
) usage guides developers to follow best practices in the use of built-in JavaScript objects.
The rule not only checks for direct calls on global objects but also tracks the referencing of these objects in a way that might lead to calling them incorrectly. This includes deep references and incorrectly invoking them as constructors, covering a broader spectrum of potential mistakes than just direct invocation.
By providing specific feedback through context.report with messageId and data detailing the name of the global object being misused, developers are not left guessing what part of their code violated the rule. This direct feedback loop can significantly speed up the debugging process and educate developers about the correct usage patterns of global objects in JavaScript.
no-object-constructor
Disallow calls to the 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
Disallow octal escape sequences in string literals
no-octal
Disallow octal literals
071
), it might be interpreted as an octal number rather than a decimal, affecting the program’s logic unexpectedly.no-param-reassign
Disallow reassigning function
parameters
This ESLint rule specifically targets a common programming pitfall where function parameters are reassigned or their properties are modified within the function body. Such practices can lead to unexpected behaviors in code, as they modify the state of arguments outside the scope of the function, potentially affecting other parts of the program that rely on the original object or value.
It provides options to customize the enforcement of this rule, such as allowing property modifications for certain variables or ignoring modifications that match specific patterns. This flexibility ensures that the rule can be adapted to different coding styles and requirements, making it practical for a wide range of projects without forcing an all-or-nothing approach.
The rule’s focus on preventing assignments to function parameters and their properties encourages the use of functional programming principles, such as immutability and pure functions. This can lead to more predictable and maintainable code, as it avoids side effects and makes functions easier to reason about, test, and debug.
By enforcing the creation and use of new objects or variables instead of modifying existing function parameters, the rule indirectly promotes better state management and data flow in applications. This practice can enhance code readability and maintainability, as it makes it clear when and where data is transformed or updated.
no-path-concat
Disallow string concatenation with __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
Disallow the unary operators ++
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
Disallow the use of process.env
The rule 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.
By discouraging the direct use of 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.
The rule helps in establishing a uniform standard across the team or project by ensuring that all developers access environment variables in the same way. This promotes consistency and reduces the chances of errors that could arise from a developer unintentionally bypassing any security or validation layers implemented for accessing these variables.
Implementing this rule as part of the project’s ESLint configuration aids in early detection of code that directly accesses 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
Disallow the use of 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
Disallow returning values from Promise executor functions
The rule specifically targets a common misunderstanding of how Promise executor functions are supposed to work by preventing the return of values from these functions, which can lead to unexpected behavior or bugs in Promise-related code. This is crucial for maintaining the integrity of asynchronous code flows.
By disallowing returns from Promise executors unless explicitly voided (with the 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.
The rule provides automatic suggestion fixes, such as prepending 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.
It considers various scenarios and syntax styles (like checking for ArrowFunctionExpression and handling void expressions differently based on the 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
Disallow the use of the __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
Disallow calling some Object.prototype
methods directly on objects
Object.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
Disallow variable redeclaration
The 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.
This rule is also important for identifying unintentional redeclarations that could overwrite variables due to hoisting in JavaScript, where variable declarations are moved to the top of their scope. Such redeclarations can cause unexpected results, especially in complex scopes.
By including the capability to identify redeclarations of both syntax and built-in globals, the rule enhances the robustness of the code. It prevents overshadowing of global variables or inadvertently redeclaring them, which can lead to confusing behavior or conflicts in the runtime environment.
The rule offers configurability (e.g., considering or ignoring built-in globals through options) that can be tailored to the project’s needs, ensuring that projects that rely on global variables, including those defined in browser or Node.js environments, can adjust the rule to fit their specific requirements. This adaptability helps in enforcing project-specific best practices without sacrificing the benefits of the rule.
no-regex-spaces
Disallow multiple spaces in regular expressions
The rule specifically targets and identifies multiple consecutive spaces within regex expressions, which are often hard to count or spot visually in code reviews or even during a casual glance at the code. This specificity helps in maintaining regex clarity and accuracy, which is crucial given the nuanced and error-prone nature of regex syntax.
By converting these multiple spaces into a quantified form (e.g., ” ”), it enforces a clearer and more maintainable approach to expressing spaces in regular expressions. This conversion can prevent misunderstandings or mistakes regarding the intended number of spaces, especially in large or complex regex patterns.
The rule includes a mechanism for safely attempting to fix detected violations by replacing consecutive spaces with their quantified form only when the pattern is exactly represented in the source code, reducing the risk of erroneous automatic fixes that could alter the regex’s intended behavior.
It smartly avoids false positives by excluding spaces within character classes and by not reporting consecutive spaces that are syntactically significant but outside the purview of what should be flagged (e.g., within strings meant to be used as regex but not directly representing regex patterns). This nuanced handling respects regex syntax rules and developer intentions, ensuring that only meaningful and correctable instances are reported.
no-restricted-exports
Disallow specified names in exports
no-restricted-globals
Disallow specified global variables
no-restricted-imports
Disallow specified modules when loaded by import
no-restricted-modules
Disallow specified modules when loaded by require
The rule helps enforce a project’s or team’s coding standards by disallowing the use of specific modules that might be considered harmful, outdated, or incompatible with the project’s architecture or security policies. For instance, preferring a more secure module over the Node.js ‘fs’ module for file operations.
It allows for custom error messages to be associated with restricted modules or patterns, providing developers with clear guidance and rationale for why a certain module is disallowed. This educational feedback can improve code quality and adherence to project standards over time.
By supporting both specific module names and pattern matching for module paths, the rule offers flexibility in defining restricted modules. This can be particularly useful in large codebases or projects with complex dependencies, allowing for a granular control over which modules can be used.
The rule’s design to allow relative path imports while restricting certain modules or patterns means that project structures can remain flexible and local module usage can be encouraged. This can promote the use of project-specific modules or libraries that conform to project standards, while still ensuring that potentially harmful external modules are avoided.
no-restricted-properties
Disallow certain properties on certain objects
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
Disallow specified syntax
This rule promotes the use of more modern, efficient, and less error-prone syntax by allowing teams to block older syntax that may lead to bugs or performance issues. For example, using for...of
instead of for...in
for arrays to avoid unintended property enumeration.
By providing the capability to define custom error messages, this rule facilitates clearer communication within a team about why certain syntaxes are discouraged, thereby aiding in educational efforts and improving codebase maintainability.
It enhances code consistency and readability across large projects by enforcing a standardized way of coding. For instance, consistently using array methods like .map()
, .forEach()
, etc., instead of various loop constructs for array operations.
The rule’s flexibility in defining restricted syntax through strings or objects with custom messages allows for precise targeting of problematic code patterns specific to the project’s requirements, which makes it a valuable tool for enforcing best practices and coding standards tailored to the project.
no-return-assign
Disallow assignment operators in return
statements
This ESLint rule specifically targets the prevention of using assignment operators directly within return
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.
The rule helps in avoiding subtle bugs that might occur when a developer unintentionally uses an assignment in a return statement, thinking it’s a comparison or another operation. This is especially relevant in JavaScript, where the similarity between assignment (=
) and equality operators (==
and ===
) can lead to errors that are hard to debug.
By enforcing the separation of actions (assignment and returning a value) into distinct statements, the rule encourages better code structure and readability. This makes it easier for other developers, or even the original author after some time, to understand the flow and purpose of the code, as each operation is explicitly stated rather than implied.
In cases where developers might intentionally use assignments in return statements for brevity, this rule forces them to reconsider their approach towards maintaining code consistency and clarity. It nudges the developer towards patterns that are widely accepted as more readable and maintainable, thus indirectly enforcing best practices within the codebase.
no-return-await
Disallow unnecessary return await
The rule helps in improving code readability by avoiding redundancy. Specifically, using 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.
It can potentially lead to performance optimizations. While the redundant use of 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.
By flagging unnecessary 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.
The rule offers automatic fix suggestions that can streamline the code refactoring process. This means developers can quickly adjust their code according to the rule’s recommendations without manually searching and removing unnecessary await
keywords, thus speeding up the development process and ensuring code style consistency across the codebase.
no-script-url
Disallow javascript:
urls
This rule helps in reducing security risks associated with the injection of malicious scripts. By disallowing the use of “javascript:” URLs, which can execute JavaScript code directly from hyperlinks, it mitigates potential attack vectors for cross-site scripting (XSS) attacks.
It enforces better coding practices by encouraging developers to use safer, more modern methods for event handling and interactivity, such as adding event listeners to DOM elements, instead of embedding JavaScript code within URL strings.
The rule promotes code clarity and maintainability. By preventing the use of “javascript:” URLs, which can make JavaScript logic harder to trace and debug, it encourages developers to structure their code in a more organized and readable manner, with JavaScript functionality clearly separated from HTML structure.
It ensures compatibility and functionality across different web browsers and environments. “javascript:” URLs are not universally supported in the same way across all platforms and can lead to inconsistent behavior. Enforcing alternative methods of implementing interactive features helps in achieving more consistent and predictable outcomes across various user agents.
no-self-assign
Disallow assignments where both sides are exactly the same
This ESLint rule, ‘no-self-assign’, directly prevents a common coding mistake where a variable is assigned to itself, which is usually unintended and indicative of a misunderstanding or typo. Implementing this rule can catch such errors early in the development process, thereby reducing debugging time and improving code quality.
By disallowing self-assignments, which are effectively no-ops (no operation), the rule helps in optimizing the codebase. Removing redundant operations can lead to slight improvements in runtime performance and resource usage, particularly in critical code paths or loops.
Using this rule encourages developers to scrutinize their use of assignment operators. Since it checks for self-assignment with not only the basic assignment operator (=
) but also with compound assignment operators like &&=
, ||=
, and ??=
, it educates developers about the proper usage of these operators and promotes coding best practices.
It improves code readability and maintainability by eliminating unnecessary lines of code. For someone reading the code, self-assignments might be confusing and could lead to the misconception that a more complex operation is being performed. By ensuring that such assignments are flagged and removed, the rule aids in keeping the codebase cleaner and more understandable.
no-self-compare
Disallow comparisons where both sides are exactly the same
This ESLint rule, ‘no-self-compare,’ specifically targets and identifies instances in the code where a variable is being compared to itself. Such comparisons are logically redundant as they will always return true, except in the unique case of NaN values in JavaScript. By catching these, it ensures that developers do not unintentionally write code that could be confusing or misleading to others, or that simply performs unnecessary operations.
By disallowing self-comparisons, this rule helps to highlight a common misunderstanding about how certain values, particularly NaN, behave in JavaScript. Since NaN is not equal to any value, including itself, using a self-comparison to check for NaN is the only valid use case. The rule encourages developers to explicitly check for NaN using isNaN() instead, leading to clearer and more correct code.
Utilizing the ‘no-self-compare’ rule aids in the optimization of the codebase. While modern JavaScript engines are very efficient at optimizing code at runtime, removing redundant comparisons can contribute to slightly faster execution times and a reduction in the overall running cost of the code, especially in large-scale applications where such checks might be numerous.
The rule includes a fix suggestion by demonstrating a meaningful replacement for a self-comparison when checking for NaN. This not only helps in correcting the error but also serves as an educational tool for developers, teaching them a more appropriate method for achieving their intended outcome. Moreover, through the encouragement of best practices and cleaner code, it indirectly contributes to the overall reliability and maintainability of the project.
no-sequences
Disallow comma operators
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
Disallow returning values from setters
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
Disallow identifiers from shadowing restricted names
This rule prevents the confusion that arises when developers redefine or shadow globally restricted names such as 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.
By disallowing the shadowing of restricted names, the rule enforces more readable and understandable code. When a restricted name is used, readers can be confident it refers to the global, well-known value rather than a local variable, reducing the cognitive load when understanding the code.
It helps in maintaining consistency and predictability across the codebase. For example, tools or libraries that rely on the global arguments
object or the eval
function will work as expected without being inadvertently affected by local redefinitions.
The rule indirectly encourages developers to choose more descriptive and meaningful names for their variables. Instead of lazily naming a variable 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
Disallow variable declarations from shadowing variables declared in the outer scope
no-spaced-func
Disallow spacing between function identifiers and their applications (deprecated)
no-sparse-arrays
Disallow sparse arrays
This ESLint rule specifically targets the use of sparse arrays, which are arrays with empty slots between elements, exemplified by the bad example [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.
By disallowing sparse arrays and suggesting the use of explicitly defined values (like 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.
The rule helps maintain code quality by enforcing explicitness in array definitions. Sparse arrays can be a source of errors, especially for developers who may not be aware that JavaScript arrays can contain empty slots. These errors might come from operations that behave differently on dense versus sparse arrays, such as map()
and forEach()
, which will skip over empty slots in sparse arrays.
The automatic reporting feature of this rule, where it uses 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
Disallow synchronous methods
This ESLint rule specifically targets the elimination of synchronous methods, which can improve the non-blocking nature of node.js operations. By disallowing methods ending with “Sync”, it ensures that code adheres to asynchronous patterns, enhancing performance especially in I/O bound applications.
The rule provides a clear mechanism to report the use of synchronous methods by leveraging a selector that matches member expressions ending in “Sync”. This specificity helps developers identify and refactor synchronous calls to asynchronous counterparts, promoting better error handling and response times in applications.
It includes an option (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.
By enforcing the refactoring of synchronous methods to their asynchronous alternatives, as demonstrated in the provided ‘fix’ example, this rule aids in preventing common pitfalls associated with blocking operations. It encourages the use of Promises and async/await syntax, which can lead to more readable and maintainable code, especially in complex, event-driven applications.
no-tabs
Disallow all 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
Disallow template literal placeholder syntax in regular strings
This rule helps to avoid unintentional use of template literal syntax in regular strings, which does not lead to interpolation. For example, it flags instances where a developer might accidentally use ${variable}
inside quotes, expecting the variable to be substituted, but since it’s not a template literal, it wouldn’t work as intended.
It promotes the correct usage of ES6 template literals when variable substitution within strings is desired. By enforcing template literals (using backticks) for variable interpolation, it ensures that developers use a syntax that will actually evaluate and insert variable values as expected.
The rule assists in preventing hard-to-find bugs related to string handling. Since the usage of ${}
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.
It aids in code clarity and maintainability by enforcing a consistent approach to string interpolation. By distinguishing between regular strings (for static text) and template literals (for dynamic text), it makes the developer’s intention clear, improving readability for others who might work on the same codebase.
no-ternary
Disallow ternary operators
no-this-before-super
Disallow this
/super
before calling super()
in constructors
super()
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
Disallow throwing literals as exceptions
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
Disallow trailing whitespace at the end of lines
Enforces a cleaner code base by eliminating trailing whitespace, which is not visually apparent but can cause unnecessary changes in version control. Trailing spaces are often invisible in many code editors and can be introduced inadvertently, leading to diffs that consist of whitespace changes only. This rule helps avoid such scenarios, making code reviews more focused on actual code changes rather than formatting issues.
Increases compatibility with tools that automatically strip trailing spaces, reducing the chance of introducing spurious differences in files. Some editors or tools have settings to remove trailing spaces on save, which can lead to unintended file changes if a project’s contributors use different development environments. Consistently disallowing trailing spaces with this ESLint rule can minimize such discrepancies.
Supports optional configurability for ignoring trailing spaces on blank lines and within comments, allowing teams to tailor the rule to their coding standards or to gradually enforce it without immediately impacting every single line of code. This flexibility can be particularly useful during the transition period when a codebase is being cleaned up or when adopting new coding styles and guidelines.
Integrates automated fixing, allowing developers to automatically correct offending lines without manual intervention. This feature significantly reduces the effort required to comply with the rule, encouraging its adoption and ensuring code consistency with minimal developer effort. It’s particularly beneficial for legacy codebases undergoing formatting standardization, as it permits mass correction without the need for extensive manual code edits.
no-undef-init
Disallow initializing variables to undefined
The rule helps in cleaning up the code by avoiding redundant initializations. Since variables in JavaScript are 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.
By enforcing this rule, it aims to improve code readability. Removing unnecessary initializations to 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.
The rule indirectly enforces a good practice of relying on the language’s default behaviors, in this case, the default 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.
This rule comes with an automated fix option for certain cases, which can save developers time during refactoring or code reviews by automatically removing unnecessary initializations. This automation helps maintain a cleaner codebase without requiring manual intervention for this specific type of issue.
no-undef
Disallow the use of undeclared variables unless mentioned in /*global */
comments
This rule helps in identifying variables that are used in the code but have not been declared, reducing runtime errors due to undefined variables. This ensures that all variables are properly initialized before use, enhancing code reliability and maintainability.
By optionally allowing the use of undeclared variables when they are explicitly mentioned in /*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.
The rule’s option to consider or ignore identifiers within a 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.
Through the reporting mechanism tied to the specific identifier causing the violation, developers are directly pointed to the source of potential bugs, enabling quicker fixes and reducing the time spent debugging issues related to undeclared variables. This targeted feedback loop is crucial for maintaining high code quality, especially in larger projects where such issues can easily go unnoticed.
no-undefined
Disallow the use of undefined
as an identifier
undefined
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
Disallow dangling underscores in identifiers
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
Disallow confusing multiline expressions
no-unmodified-loop-condition
Disallow unmodified loop conditions
Prevents the risk of infinite loops which can occur if the loop condition variables are not modified within the loop. In the provided “bad” example, the variable attempts
is not modified inside the loop, which could potentially lead to an infinite loop if checkInput
never returns true
.
Enhances code readability and maintainability by ensuring that loops are written with clear progression criteria, making it easier for developers to understand how and when the loop will terminate.
Helps identify logical errors at an early stage, where a developer might have unintentionally forgotten to update the loop condition. This rule flags such lapses, enabling quick fixes that could otherwise lead to hard-to-debug runtime issues.
Encourages best practices in programming by enforcing a pattern where the conditions for loop continuation are actively controlled within the loop body, promoting the writing of safer and more efficient code.
no-unneeded-ternary
Disallow ternary operators when simpler alternatives exist
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
Disallow loops with a body that allows only one iteration
The rule specifically targets loop constructs that are set up in such a way that they can only iterate once before hitting a condition that forces them to exit. This is particularly useful to identify and correct loops that, due to their logic, do not fulfill their intended iterative purpose which can help developers catch logical errors or inefficiencies in their code early.
By identifying loops that will only run once, this rule helps in optimizing the performance of the code. Unnecessary loops can add overhead by setting up loop controls and evaluating conditions which ultimately are redundant, thereby wasting computational resources.
The rule helps in improving code readability and maintainability by pointing out sections of the code that are logically complex or have misleading constructs. For example, a loop that only runs once might suggest an algorithm that could be simplified or a misunderstanding of how loop constructs work, leading to clearer and more maintainable code once addressed.
It reduces the risk of introducing subtle bugs related to the misunderstanding of loop behavior. A developer might expect a loop to process multiple elements or perform iterations under certain conditions, but due to misconfiguration, it exits prematurely. Highlighting these scenarios ensures the loop’s logic aligns with the developer’s intentions, thereby reducing the likelihood of bugs related to control flow.
no-unreachable
Disallow unreachable code after return
, throw
, continue
, and break
statements
The rule specifically targets and eliminates unreachable code that follows return
, 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.
By disallowing unreachable code, it directly contributes to cleaner codebases, making maintenance and debugging easier. When developers understand that certain sections of code are guaranteed not to be executed, they can focus on optimizing and debugging the reachable parts of their code more effectively.
The rule includes logic to handle various statement types, including function declarations, class declarations, loops, and conditional statements, which makes it comprehensive in detecting unreachable code across a wide array of JavaScript syntax. This thoroughness ensures that most, if not all, cases of unreachable code can be identified and reported, regardless of the specific control flow constructs used.
It incorporates a sophisticated way of tracking code paths and segments, including managing current code path segments and distinguishing consecutive statements. This allows for accurate identification and reporting of unreachable code, even in complex code structures. By doing so, it helps maintain high code quality standards and supports best practices in programming by ensuring that control flow in applications is logical and efficient.
no-unsafe-finally
Disallow control flow statements in finally
blocks
Ensures predictability in error handling: Using control flow statements like return
, 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.
Improves code readability and maintainability: By disallowing control flow statements in 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.
Prevents unintended consequences: The use of control flow statements in 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.
Encourages proper usage of 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
Disallow negating the left operand of relational operators
This rule helps to prevent logical errors in the code where developers might unintentionally negate the left operand of relational operators (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
.
It enhances code readability and maintainability by enforcing a clearer syntax for negations with relational operators. By requiring explicit parentheses when intending to negate the result of a relational operation, it becomes immediately clear to anyone reading the code what the intended logic was, reducing the cognitive load and potential for misinterpretation.
The rule includes a suggestion mechanism that can automatically fix detected issues by adding parentheses where necessary. This feature can save developer time and reduce the likelihood of human error during manual correction, making code refactoring and review processes more efficient.
By allowing configuration options such as 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
Disallow use of optional chaining in contexts where the undefined
value is not allowed
Ensures arithmetic operations are safe by preventing the addition of undefined
values which can lead to NaN errors. For instance, const result = obj?.b + 5;
might result in undefined + 5
without this rule.
Enhances code readability and maintainability by enforcing the explicit handling of potentially undefined
values when using optional chaining, which can otherwise lead to unexpected behaviors or bugs.
Promotes the use of nullish coalescing operator (??
) over logical OR (||
) with optional chaining to explicitly handle undefined
and null
values, ensuring that fallback values are used only in the intended cases.
Prevents the erroneous return of 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
Disallow 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
Disallow unused labels
no-unused-private-class-members
Disallow unused private class members
This rule helps identify and remove private class members (like methods and properties) that are declared but not used within the class. By enforcing the removal of unused private members, it ensures that the class code remains clean and concise, improving code readability and maintainability.
It reduces the overall memory footprint of your application. Unused private class members, particularly methods, can still occupy memory space even if they are never invoked. Removing these can lead to a slight performance improvement, especially in large applications with many class definitions.
The rule discourages the practice of leaving dead code in the project, which can cause confusion for developers. When a new developer encounters an unused private member, they might spend unnecessary time figuring out its purpose or hesitate to remove it due to uncertainty about its relevance, slowing down development.
Enforcing this rule can also indirectly encourage better coding practices and architecture decisions. When developers know that unused private members will be flagged, they are more likely to carefully plan their class designs and member usage, leading to more thoughtfully constructed and efficient codebases.
no-unused-vars
Disallow unused variables
no-use-before-define
Disallow the use of variables before they are defined
Prevents potential ReferenceErrors caused by using variables or functions before their declaration, improving the reliability of the code. By ensuring all references are defined before use, this rule helps avoid runtime errors that are difficult to debug.
Enhances code readability and maintainability by enforcing a more predictable structure. When variables and functions are defined before they are used, it becomes easier for developers to follow the flow of logic within the codebase, making the code easier to understand and maintain.
Supports the correct understanding and use of the Temporal Dead Zone (TDZ) for let and const declarations in JavaScript. By disallowing the use of variables before they are defined, this rule helps developers avoid subtle bugs related to the TDZ, where let and const variables exist but aren’t initialized.
Allows for more efficient code optimization by JavaScript engines. When variables and functions are used after they are defined, it becomes easier for JavaScript engines to optimize the code, potentially leading to performance improvements in the execution of the code.
no-useless-backreference
Disallow useless backreferences in regular expressions
^(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
Disallow unnecessary calls to .call()
and .apply()
The rule specifically targets the elimination of redundant usage of .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.
By detecting and discouraging the use of .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.
Since .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.
The rule also indirectly educates developers about the correct use cases for .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
Disallow unnecessary catch
clauses
no-useless-computed-key
Disallow unnecessary computed property keys in objects and classes
Promotes code cleanliness by discouraging the use of unnecessary computed property keys, leading to more readable and straightforward object and class syntax. When property names are statically determinable, using computed keys adds unnecessary complexity.
Enhances code performance slightly; accessing properties using computed keys is a tad slower than accessing them directly. By discouraging unnecessary computed keys, this rule may contribute to micro-optimizations, especially in performance-critical applications.
Prevents potential bugs related to using dynamic property names when static ones are intended. In some cases, developers might use computed keys by habit or misunderstanding, potentially leading to unintended dynamic behavior. By enforcing simpler syntax, this rule helps maintain the intended static nature of property definitions.
Improves auto-fixable coding patterns, allowing developers to automatically clean up and simplify their code bases with tooling support. This rule comes with an auto-fix option that can correct violations without manual intervention, thereby saving time and reducing the potential for human error during refactoring or code review processes.
no-useless-concat
Disallow unnecessary concatenation of literals or template literals
Ensures code readability by eliminating the need to decipher unnecessary string concatenations, which can simplify understanding string values at a glance. For example, instead of piecing together several concatenated pieces, a developer can see the intended string in one cohesive unit.
Improves performance by reducing the number of runtime concatenation operations, especially relevant in tight loops or high-performance code sections. Concatenating literals at compile time can shave off precious milliseconds in critical performance paths.
Encourages the use of template literals for variable inclusion within strings, prompting developers towards modern JavaScript features that enhance code clarity and functionality. This also indirectly promotes consistency in how dynamic strings are handled across the codebase.
Helps in identifying potentially unintended concatenations that could be a result of typos or logic errors, thus preventing bugs related to string processing. For example, it flags cases where developers might accidentally concatenate strings that were meant to be separate entities, thus allowing early correction.
no-useless-constructor
Disallow unnecessary constructors
no-useless-escape
Disallow unnecessary escape characters
no-useless-rename
Disallow renaming import, export, and destructured assignments to the same name
This rule helps maintain code clarity and simplicity by eliminating redundant syntax, which can make the code less verbose and easier to read. Renaming an import, export, or destructured assignment to the same name adds unnecessary complexity without any benefit.
It ensures consistency across the codebase by preventing developers from using an unnecessary rename syntax. This consistency can be particularly beneficial for teams working on large projects, as it makes the code more homogenous and understandable for everyone involved.
By disallowing unnecessary renaming, this rule can indirectly prevent potential typos or errors that might occur during the renaming process. For example, when manually renaming variables, there’s a risk of introducing a typo that could lead to bugs. Not needing to rename reduces this risk.
The rule provides automatic fix capabilities for detected issues, which can save developer time and effort. When the rule detects unnecessary renaming, it can automatically correct it to the simpler syntax without renaming. This automated fix reduces the manual work required and helps in maintaining cleaner code more efficiently.
no-useless-return
Disallow redundant return statements
Ensures cleaner code by eliminating redundant return statements, which in turn may make the code easier to read and maintain. For instance, removing unnecessary return;
statements at the end of functions simplifies the function’s logic.
Helps in potentially reducing the cognitive load for developers reading the code by removing statements that have no effect on the code’s execution. This can also make it easier to understand the intended control flow of the function.
By flagging useless return statements, it encourages developers to consider the necessity of their control flow statements. This could lead to more thoughtful coding practices, where developers aim for concise and efficient code.
May indirectly improve performance in certain JavaScript engines by reducing the number of instructions that need to be executed. Although the impact might be minimal, removing unnecessary statements contributes to overall code optimization.
no-var
Require let
or const
instead of var
Promotes block-scoped variable declarations: This rule enforces the use of 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.
Encourages immutable data patterns: By requiring 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.
Prevents temporal dead zone (TDZ) issues: This rule includes logic to check for self-references in the TDZ, which is the time after hoisting but before the variable is initialized. Given that 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.
Minimizes scope-related errors: The detailed conditions under which the rule does not automatically fix a 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
Disallow void
operators
void
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
Disallow specified warning terms in comments
no-whitespace-before-property
Disallow whitespace before properties
This rule ensures consistency in object property access notation by disallowing whitespace before the dot or bracket notation, making the code more readable and easier to understand. For example, turning object .property
or array [index]
into object.property
or array[index]
, which is the standard notation.
The rule prevents syntax errors and potential runtime issues that may arise from unusual whitespace usage before properties, such as when attempting to call a method on a number literal with a space (5 .toString()
), ensuring the integrity of the code’s execution.
It automates the removal of unintended whitespaces in property access expressions, which not only cleans up the code but also saves time during code review and manual refactoring processes, maintaining a cleaner and more professional codebase.
The rule is designed to be intelligent by not applying fixes in certain cases where it could introduce errors or when comments exist between tokens, thereby respecting the developer’s intentions and possibly highlighting unconventional use cases that warrant a manual review.
no-with
Disallow with
statements
with
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
Enforce the location of single-line statements
This ESLint rule enforces a consistent styling for where single-line statements should be located relative to their control statements (such as 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.
By providing configuration options that allow teams to enforce single-line statements either beside or below their control statements (or allow any position), this rule offers flexibility to adhere to an organization’s specific coding standards. Such adaptability ensures that the rule can be tailored to the preferences of different teams or projects, promoting a uniform coding style that aligns with organizational best practices.
The rule includes an automatic fix feature, which can correct misaligned single-line statements according to the configured preference (either to the ‘beside’ or ‘below’ position). This automated fixing capability can save developers time during both the development and code review processes by reducing manual effort required to adhere to styling rules and allowing them to focus more on logic and functionality rather than formatting inconsistencies.
The scope of this rule covers several control statement types (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
Enforce consistent line breaks after opening and before closing braces
object-curly-spacing
Enforce consistent spacing inside braces
The rule assists in maintaining a uniform appearance of object literals, destructuring assignments, and import/export specifiers across a codebase by enforcing or forbidding spaces inside the curly braces, which can lead to improved readability and easier maintenance due to consistency.
It automatically corrects detected violations by adding or removing spaces as appropriate, thereby saving time during code reviews and reducing the burden on developers to manually fix style issues related to brace spacing.
By offering configurable exceptions for arrays and objects within objects, the rule provides flexibility, allowing teams to adopt a spacing policy that best suits their preferences for certain complex structures while still enforcing a general rule.
The rule helps prevent potential merge conflicts and diff noise in version control systems caused by inconsistent spacing inside braces among different code contributions, thus facilitating smoother collaboration and integration processes.
object-property-newline
Enforce placing object properties on separate lines
object-shorthand
Require or disallow method and property shorthand syntax for object literals
one-var-declaration-per-line
Require or disallow newlines around variable declarations
one-var
Enforce variables to be declared either together or separately in functions
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
Require or disallow assignment operator shorthand where possible
The rule encourages the use of assignment operator shorthand (+=
, *=
, %=
, 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.
It includes a mechanism to safely apply fixes that take into account both the presence of comments between tokens and the precedence of operations, ensuring that automatic corrections do not unintentionally change the logic of the code. This careful approach minimizes the risk of introducing bugs when the rule’s suggestions are applied.
The rule differentiates between commutative and non-commutative operations, allowing it to identify cases where shorthand can be applied without altering the execution order of expressions. This distinction is crucial for maintaining the correctness of operations that depend on the order of operands (e.g., a = b * a
being different from a *= b
in certain contexts).
It offers configurability to enforce or prohibit the use of operator assignment shorthands, allowing teams to adopt the style that best suits their codebase. This flexibility makes the rule adaptable to various coding guidelines and preferences, enabling teams to enforce consistency in code style regarding assignment operations.
operator-linebreak
Enforce consistent linebreak style for operators
padded-blocks
Require or disallow padding within blocks
The rule helps in enforcing a consistent code format regarding padding within blocks, switches, and classes. This means that depending on the project’s coding standards, it can require or disallow empty lines at the beginning and end of a block, thus making the code more readable and maintaining a standard look across the codebase.
It provides a configurable option to allow single-line blocks without padding, which can be particularly useful for short, simple blocks of code where padding might make the code unnecessarily lengthy or visually cluttered.
The rule’s design to check and potentially auto-fix padding in different structures (blocks, switches, classes) makes it versatile and applicable to various aspects of JavaScript programming, ensuring that all parts of the code can adhere to the specified padding rules.
Since the rule includes options to automatically fix violations by adding or removing padding as necessary, it can save developers time during the coding process and help reduce the potential for manual errors, making the code cleaner and more efficient to execute.
padding-line-between-statements
Require or disallow padding lines between statements
By enforcing consistent padding lines between statements, this rule significantly improves the readability of the code, making it easier for developers to distinguish between separate blocks of logic or sections of code. In the provided “fix” example, the visual separation between variable declaration, console logs, and the conditional statement clearly delineates the distinct actions being performed.
The rule aids in maintaining a uniform code style across a project, or even across teams if the configuration is shared. This uniformity reduces cognitive load when switching between files or projects, as developers can expect a consistent structure in how code is formatted, specifically regarding the spacing between statements.
It prevents likely merge conflicts and simplifies code reviews by standardizing the amount of whitespace between statements. Code differences that result from disparate uses of padding lines (for instance, one developer using two newline characters where another uses one) can create unnecessary merge conflicts. By enforcing a specific style, this rule helps to minimize such avoidable issues.
The rule is configurable to match different coding styles and preferences, improving its adaptability to various projects or team guidelines. Since it can interpret array of configurations for matching different types of statements (e.g., variable declarations, function calls, if statements), it offers flexibility in enforcing line padding in a way that aligns with the unique stylistic choices or readability goals of a project. This adaptability ensures that teams can enforce padding where it’s most beneficial without compromising on the broader stylistic choices of their codebase.
prefer-arrow-callback
Require using arrow functions for callbacks
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
Require const
declarations for variables that are never reassigned after declared
const
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
Require destructuring from arrays and/or objects
prefer-exponentiation-operator
Disallow the use of 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
Enforce using named capture group in regular expression
prefer-numeric-literals
Disallow parseInt()
and Number.parseInt()
in favor of binary, octal, and hexadecimal literals
This ESLint rule encourages the use of binary, octal, and hexadecimal literals instead of parseInt()
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.
The rule includes an autofix feature that automatically replaces calls to 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.
By disallowing 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.
It carefully checks that replacing 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
Disallow use of Object.prototype.hasOwnProperty.call()
and prefer use of Object.hasOwn()
Avoids indirect method access: The rule discourages the use of 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.
Encourages modern method adoption: Promoting the use of 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.
Improves performance potential: While the exact performance implications can depend on JavaScript engine optimizations, using 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.
Increases code safety and readability: By enforcing the use of 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
Disallow using Object.assign with an object literal as the first argument and prefer the use of object spread instead
Ensures modern JavaScript syntax is used: By preferring the use of object spread ({...obj}
) over Object.assign({}, obj)
, this rule encourages the adoption of ES6+ syntax, which is more concise and readable for merging objects.
Improves performance: Object spread syntax can lead to performance improvements in many JavaScript engines compared to Object.assign
when merging objects, as it’s more optimized for this specific use case.
Reduces unnecessary complexity: Using object spread simplifies the syntax and avoids the verbosity of Object.assign
, particularly when the first argument is an empty object literal. This can make code easier to read and maintain.
Avoids unintended side effects: When using 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
Require using Error objects as Promise rejection reasons
prefer-reflect
Require Reflect
methods where applicable
Encourages the use of Reflect
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.
Helps in avoiding some of the pitfalls and inconsistencies associated with the traditional methods like 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.
Facilitates operations on objects without directly invoking their internal methods, serving as a safer alternative for operations like property deletion (Reflect.deleteProperty
vs delete
operator). This is particularly useful in scenarios involving proxied objects, where direct operations might inadvertently trigger traps.
Provides an opportunity to easily configure exceptions for specific cases where the developer might intentionally prefer the traditional method over 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
Disallow use of the RegExp
constructor in favor of regular expression literals
RegExp
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
Require rest parameters instead of 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
Require spread operators instead of .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
Require template literals instead of string concatenation
The rule promotes the use of template literals over string concatenation, which leads to more readable and maintainable code, especially when embedding variables within strings. For instance, the rule would transform "Your full name is: " + firstName + " " + lastName + "."
into Your full name is: ${firstName} ${lastName}.
, which is easier to comprehend at a glance.
It automatically handles escaping of characters that might otherwise be interpreted as part of the template syntax (${}
and backticks), when converting string concatenations into template literals. This reduces the risk of introducing syntax errors or unintended behavior during the conversion process.
By encouraging the use of template literals, this rule indirectly supports better string formatting practices, such as multiline strings and including expressions within strings without the need for concatenation operators (+
). This can lead to cleaner code, particularly when dealing with long strings or strings that require dynamic content.
The rule provides autofix functionality, meaning that in many cases, it can automatically convert code that uses string concatenation to use template literals instead. This not only saves developer time but also helps in enforcing a consistent coding style across a codebase without requiring manual intervention for such conversions.
quote-props
Require quotes around object literal property names
This rule caters specifically to enhancing code readability and consistency by requiring quotes around object literal property names, making it easier for developers to distinguish between property names and other language constructs.
It helps avoid potential errors by ensuring that keywords or reserved words that happen to be used as object property names are quoted, which is especially helpful to maintain compatibility across different ECMAScript versions or environments where an identifier might be interpreted incorrectly.
The rule’s options allow for flexibility between quoting all property names, quoting as needed (only when it would otherwise result in a syntax error or misinterpretation), or maintaining consistency throughout the object, which can be critical for projects requiring a specific coding style for maintainability and to avoid bikeshedding.
It includes automatic fix capabilities to correct inconsistencies or unnecessary quoting, thereby saving developer time and reducing the likelihood of human error during manual code reviews or corrections, helping to maintain a clean and stylistically consistent codebase with minimal effort.
quotes
Enforce the consistent use of either backticks, double, or single quotes
backticks
, double
, or single
quotes) throughout the codebase, reducing the cognitive load when reading and understanding code.radix
Enforce the consistent use of the radix argument when using parseInt()
Prevents ambiguity in numeric conversions: The radix parameter specifies the base of the numerical string used in 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.
Promotes code readability and maintainability: By requiring the radix argument, it becomes immediately clear to anyone reading the code which numerical base is intended for the conversion. This clarity makes the code easier to understand and maintain, especially for teams or in public code bases where people with different levels of expertise may interact with the code.
Enforces best practices automatically: Instead of relying on manual code reviews or developer memory to ensure the radix is provided, this ESLint rule automates the enforcement. Automatic checks like this help maintain code quality and adhere to best practices without extra effort from developers.
Provides actionable feedback with autofix suggestions: When the rule identifies a violation, it doesn’t just flag the issue but also suggests a fix, specifically to add a radix of 10 for decimal conversions if missing. This not only educates developers about the issue but also provides a quick way to resolve it, improving the development workflow and speeding up the process of addressing linting feedback.
require-atomic-updates
Disallow assignments that can lead to race conditions due to usage of 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
Disallow async functions which have no await
expression
The rule enforces the use of await
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.
By disallowing async functions that do not include an 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.
The rule aids in code readability and maintainability by ensuring that the use of 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.
Enforcing this rule can help in preventing potential errors in the flow of asynchronous code. For example, a developer might mark a function as async with the intention of using await
but forget to do so. This rule would catch such oversights, potentially saving time in debugging asynchronous logic issues.
require-jsdoc
Require JSDoc comments
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
Enforce the use of u
or v
flag on RegExp
u
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
Require generator functions to contain yield
yield
keyword, promoting correctness in asynchronous or iterable operations.rest-spread-spacing
Enforce spacing between rest and spread operators and their expressions
semi-spacing
Enforce consistent spacing before and after semicolons
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
Enforce location of semicolons
Ensures consistency in semicolon placement throughout the code, which can aid in readability and maintenance by following a standardized format, whether at the beginning or the end of lines based on the configured option.
Helps prevent common syntax errors or parsing issues that might occur from incorrect semicolon placement, particularly in languages where semicolons can change how lines or blocks of code are interpreted.
Facilitates easier code minification and concatenation processes, as consistent and correct semicolon placement can prevent runtime errors when scripts are compressed into a single line.
Assists in the automatic fixing of semicolon-related styling issues, thus saving developer time and effort in code reviews or manual corrections, and maintaining a cleaner codebase with less effort.
semi
Require or disallow semicolons instead of ASI
sort-imports
Enforce sorted import declarations within modules
The rule enforces a consistent ordering of import declarations within a module, which can improve readability and maintainability of code. By having a predefined sort order (e.g., “none”, “all”, “multiple”, “single”), developers can easily find and manage imports, reducing the cognitive load when working with modules.
It offers configurable options to ignore case sensitivity and the sorting of member names within import declarations. This flexibility allows teams to tailor the rule to their coding standards and preferences, ensuring that imports are sorted in a way that makes the most sense for their project’s structure and naming conventions.
The rule supports separating import groups with blank lines and resetting the sorting logic per group if configured with 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.
It includes functionality to automatically fix unsorted imports, saving developers time and effort that would otherwise be spent manually sorting imports. This auto-fixing capability streamlines the development process, ensuring that imports adhere to the specified order without requiring manual intervention and thus reducing the chance of human error.
sort-keys
Require object keys to be sorted
sort-vars
Require variables within the same declaration block to be sorted
space-before-blocks
Enforce consistent spacing before blocks
The rule ensures a uniform appearance across the codebase by enforcing or disallowing space before blocks, contributing to increased readability and maintainability. This consistency helps developers quickly understand the structure and flow of the code, regardless of the specific details of each block.
By offering configuration options like “always” or “never” for functions, keywords, and classes, it allows teams to align the rule with their specific coding standards or style guides. This flexibility ensures that the rule adapts to the preferred practices of different development environments, enhancing team cohesion and productivity.
The rule includes logic to avoid conflicts with other spacing-related ESLint rules (e.g., 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.
Through its automatic fix functionality, it not only identifies inconsistencies but also offers the means to correct them automatically. This feature significantly speeds up the process of adhering to the project’s coding standards, as it reduces the manual effort required from developers to align their code with the enforced style rules, thereby allowing them to focus more on solving complex problems rather than on formatting issues.
space-before-function-paren
Enforce consistent spacing before function
definition opening parenthesis
This rule ensures a consistent appearance in code by either enforcing or prohibiting spaces before function parentheses, making the codebase easier to read and maintain. Applying this rule across a project helps to standardize the formatting of function declarations and expressions, including arrow functions, which can reduce cognitive load when reading through code.
It allows for customizable configurations, meaning a team can decide whether they want to always have a space before the parenthesis, never have it, or ignore the rule for certain functions (e.g., async arrow functions, named functions, or anonymous functions). This flexibility lets the rule adapt to a project’s specific coding style preferences or guidelines.
The rule accounts for exceptions and nuances in coding styles, such as not applying fixes if there’s a single-line comment between the function keyword and its parentheses. This consideration helps to maintain the readability and intent of comments without inadvertently introducing syntax errors or misinterpretations of code.
It provides automatic fixing capabilities, which can save developers time during code refactoring or initial writing. For instances where a space is missing and should be added (or vice versa), the rule’s fixer can automatically adjust the code to comply with the project’s chosen configuration, helping to speed up the development process and ensure code style consistency without manual effort.
space-in-parens
Enforce consistent spacing inside parentheses
The rule explicitly enforces a consistent spacing practice inside parentheses across the codebase, which enhances readability and standardizes the format of code for all developers involved. Given the examples, without this rule, code can appear cluttered and inconsistent, making it harder to read and maintain.
It provides flexibility through exceptions, allowing developers to configure the rule to ignore specific cases such as empty parentheses, or when they contain specific characters (, [], ()). This adaptability means that while promoting consistency, the rule can be tailored to fit the particular styling guides or preferences of a project or team.
The rule includes automatic fix functionality that can correct spacing issues by either inserting or removing spaces as needed. This not only saves time during the development process but also helps in ensuring that code complies with the project’s styling guidelines without requiring manual intervention for such stylistic concerns.
The exceptions management within the rule logic allows for fine-tuning the enforcement of spaces within parentheses. For instance, it differentiates between opening and closing parentheses and offers an opportunity to handle empty parentheses differently. This level of detail in exception handling helps in addressing nuanced styling preferences, thereby providing a more customizable and thorough approach to enforcing code style rules specific to spacing within parentheses.
space-infix-ops
Require spacing around infix operators
=
, +
, ?
, :
, 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
Enforce consistent spacing before or after unary operators
The rule specifically targets the enforcement of consistent spacing around unary operators, which is crucial for maintaining readability and a uniform code style. By focusing on both word-based (like 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.
This rule offers configurability for projects through 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.
The inclusion of a fixer function within the rule’s logic enables automatic correction of spacing inconsistencies, saving developers time during code reviews and reducing manual effort required to adhere to stylistic guidelines. This feature significantly increases the utility of this ESLint rule by not only identifying but also resolving spacing issues.
The rule smartly handles special cases, such as the ”!!” for converting a value to a boolean, by including logic to avoid flagging them as errors or attempting an incorrect fix. This attention to detail prevents potential bugs introduced by automated fixes and acknowledges the usage patterns of unary operators in JavaScript, ensuring that the rule does not enforce spacing in a manner that could alter the intended functionality of the code.
spaced-comment
Enforce consistent spacing after the //
or /*
in a comment
This ESLint rule ensures consistency in the use of spacing after comment markers (//
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.
The rule is configurable to accommodate different coding style preferences, either enforcing or disallowing a space immediately after the comment syntax. This flexibility allows teams to adopt a style that best suits their standards and ensures that the linter supports rather than obstructs their preferred coding practices.
It supports automatic fixing of detected issues, which means that developers can quickly correct their code to comply with the enforced style without manually editing each comment. This auto-correction feature not only saves time but also helps maintain consistency throughout the codebase without additional effort from the developers.
The rule handles both line and block comments and is smart enough to consider exceptions and markers. This detailed approach ensures that special cases, such as JSDoc comments or other annotations that might utilize a different spacing rule, are correctly identified and treated according to the project’s configuration. This prevents the misapplication of the rule in contexts where a deviation from the norm is intentional and beneficial for clarity.
strict
Require or disallow strict mode directives
'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
Enforce spacing around colons of switch statements
symbol-description
Require symbol descriptions
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
Require or disallow spacing around embedded expressions of template strings
template-tag-spacing
Require or disallow spacing between template tags and their literals
fix
function can automatically adjust spacing to meet the rule’s requirements without developer intervention.unicode-bom
Require or disallow Unicode byte order mark (BOM)
Ensuring consistency in file encoding across a project: This rule can help enforce a consistent approach to the presence or absence of a Unicode Byte Order Mark (BOM) in project files, reducing potential issues when files are exchanged between different environments and editors that may have differing defaults for handling BOMs.
Facilitating team or project-specific coding standards: By allowing configuration to require or disallow a BOM, this rule supports adherence to agreed coding standards within a team or project, ensuring that all contributors are aligned on this aspect of file formatting.
Avoiding errors related to BOM in JavaScript files: Since the presence or absence of a BOM can affect the way files are parsed and executed in some JavaScript engines or when served to web browsers, enforcing a consistent policy helps prevent subtle, hard-to-diagnose errors related to character encoding.
Automated fixability for easy compliance: The rule offers an automated fix option, capable of inserting or removing the BOM as required. This eases the process of bringing files into compliance with the project’s chosen standard, saving developer time and reducing the likelihood of human error during manual editing.
use-isnan
Require calls to isNaN()
when checking for NaN
This rule specifically addresses the common misconception in JavaScript that 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.
In switch cases, it’s easy to mistakenly include a case for 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
.
When using methods like .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()
.
By enforcing checks for 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
Enforce valid JSDoc comments
@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
Enforce comparing typeof
expressions against valid strings
vars-on-top
Require var
declarations be placed at the top of their containing scope
Ensures a consistent structure within a function or block by having var
declarations at the top. This structure can make the code easier to read and understand, since variable declarations are not scattered throughout the function.
Helps in avoiding potential hoisting issues. JavaScript hoists 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.
Facilitates the identification of variables that are being used throughout a function or block scope. When variables are declared at the beginning, it provides a clear list of what variables are available, improving code maintainability and reducing the chance of redeclaring variables.
Can contribute to slightly improved performance in JavaScript engines that optimize based on the predictability of the code’s structure. While modern engines are efficient at optimizing various patterns, consistent patterns like declaring variables at the top could theoretically make the initial parsing phase slightly faster.
wrap-iife
Require parentheses around immediate function
invocations
The rule enforces a consistent syntax for wrapping immediately invoked function expressions. By either requiring parentheses around the IIFE itself or around the function expression and its invocation, it promotes readability and maintainability of code that uses IIFEs for scoping or executing functions immediately.
It provides options for flexibility in styling—either “inside” or “outside” wrapping of the parentheses. This allows teams or projects to choose the style that best suits their readability preferences or to align with their established coding standards, thus supporting consistency across the codebase.
The rule includes an option to include function prototype methods like call
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.
It offers auto-fix functionality that automatically adjusts the positioning of parentheses to conform to the selected style. This feature saves developers time during both the initial writing and subsequent code reviews by reducing manual effort in formatting and ensuring consistency across IIFEs in the codebase. With this, the rule not only enforces a style but also assists in the correction and standardization of existing and newly written code.
wrap-regex
Require parenthesis around regex literals
This ESLint rule is designed specifically to ensure readability and clarity when regular expressions (regex) are used in a chain of method calls. For example, it modifies /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.
The rule prevents potential confusion regarding the precedence of operations when a regex is involved in expressions. Since /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.
By enforcing regex literals to be wrapped in parentheses when used in member expressions, this rule aids in maintaining a consistent coding style across a codebase. This consistency can help new team members or contributors to understand the code faster and contribute more effectively.
The automated fixing feature of this rule, which adds the necessary parentheses around regex literals, simplifies code refactoring efforts. Developers do not have to manually search and wrap regex literals, saving time and reducing the risk of introducing syntax errors during manual code modifications.
yield-star-spacing
Require or disallow spacing around the *
in yield*
expressions
yield*
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
Require or disallow “Yoda” conditions
The rule specifically targets “Yoda” conditions, where the literal value is placed before the variable (e.g., 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.
It provides options to enforce or disallow Yoda conditions universally across the codebase, except in cases involving range checks or equality checks, where readability might not be significantly impaired. This flexibility allows teams to adapt the rule to their coding standards while still preventing inconsistency in condition formatting.
The rule includes functionality to automatically correct violations by flipping the sides of the expression to match the configured preference (either always enforcing Yoda conditions or always disallowing them). This auto-fixing feature facilitates codebase consistency without requiring manual intervention for each identified issue.
By considering exceptions for range tests and allowing configurations for only equality comparisons, the rule acknowledges that in some scenarios, Yoda conditions might enhance clarity or align with a team’s specific preferences. This nuanced approach ensures that the rule can be applied in a way that improves code quality and readability without being overly prescriptive.