Get Started
- CodeAnt AI
- Control Center
- Pull Request Review
- IDE
- Compliance
- Anti-Patterns
- Code Governance
- Infrastructure Security Database
- Application Security Database
Eslint
Enforce getter and setter pairs in objects and classes
// Object with getter but no setter
const obj1 = {
get a() {
return this._a;
}
};
// Class with setter but no getter
class MyClass {
set a(value) {
this._a = value;
}
}
-
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.
Enforce linebreaks after opening and before closing array brackets
const fruits = ['apple', 'banana', 'cherry'];
- The rule encourages readability and maintainability by enforcing clear visual separation for array elements across multiple lines when necessary, making it easier for developers to scan and comprehend the structure of array data within the code.
- It provides configurable options allowing teams to enforce a coding style that is consistent with their project guidelines or personal preference, regarding how arrays should be formatted, hence promoting coding standards across projects.
- By including automatic fixing capabilities, it not only points out stylistic issues but also provides a quick solution to adhere to the rule without manually adjusting the array brackets, thus saving time and effort during the development and review processes.
- The rule can adapt based on the array’s content or length by considering options like
multiline
andminItems
, 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.
Enforce consistent spacing inside array brackets
// Bad Example: Inconsistent spacing inside array brackets
const myArray1 = [1,2,3];
const myArray2 = [ 1,2,3 ];
const myArray3 = [1, 2, 3];
-
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.
Enforce return
statements in callbacks of array methods
const numbers = [1, 2, 3, 4];
const doubled = numbers.map((num) => {
console.log(num * 2); // Incorrect use: callback does not return a value
});
-
This ESLint rule ensures all callbacks of array methods like
.map()
,.filter()
, etc., include areturn
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
, andallowVoid
allows for tailored enforcement, accommodating different coding styles or project requirements. For instance,checkForEach
can enforce stylistic consistency by disallowing returns inforEach
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.
Enforce line breaks after each array element
const numbers = [1, 2, 3, 4];
- Ensures consistency in how array elements are separated, which can improve readability, especially in large arrays or arrays containing complex elements.
- Offers customizable settings (e.g.,
multiline
,minItems
), allowing teams or projects to tailor the rule to match their coding style guidelines, thus maintaining codebase uniformity. - Automatically fixable, meaning it can reformat arrays to meet the specified criteria without manual intervention, saving time during both development and code review processes.
- Helps in identifying potential errors or misunderstandings in array structures by enforcing a clear visual separation of elements, making the code easier to debug and review.
Require braces around arrow function bodies
// as-needed configuration, but using braces unnecessarily for a single return statement
const addOne = (a) => {
return a + 1;
};
// never configuration, but written with braces
const sum = (a, b) => {
return a + b;
};
- Enforcing a consistent arrow function syntax helps maintain readability and reduces ambiguity in code structure, particularly in distinguishing between single-expression returns and more complex function bodies.
- This rule can prevent syntax errors related to Automatic Semicolon Insertion (ASI) by enforcing or disallowing braces, thus making the code more predictable and avoiding hard-to-debug errors that can occur when JavaScript automatically inserts semicolons.
- By allowing configuration options like “always”, “as-needed”, or “never”, it provides flexibility to adapt the code style rules based on project-specific guidelines or personal preference, ensuring the rule can be effectively applied across different coding environments or scenarios.
- It aids in optimizing code succinctness and clarity by identifying instances where braces and the
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.
Require parentheses around arrow function arguments
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(number => number * 2);
- Ensures consistency in syntax across arrow functions by mandating that parentheses are used around arguments, making the code base easier to read and maintain, especially when the arrow function’s complexity grows or needs modifications.
- Facilitates the addition of parameters to an arrow function in the future without altering the syntax, as parentheses already enclose the existing parameter. This preemptive structuring can streamline future development efforts and minimize syntax errors.
- Avoids ambiguity in the code when arrow functions with a single parameter are used in conjunction with advanced JavaScript features such as types or default values, where the absence of parentheses could lead to misunderstandings about the function’s intended behavior.
- Improves automatic code fixing capabilities, as the rule explicitly provides the logic to add or remove parentheses as needed based on the function’s structure, thereby assisting developers in adhering to the style guide with minimal manual intervention.
Enforce consistent spacing before and after the arrow in arrow functions
const add = (a,b)=>a+b;
- The rule ensures consistency in the codebase by enforcing a uniform appearance of arrow functions, making the code easier to read and maintain, as exemplified by transforming
const add = (a,b)=>a+b;
to the more readableconst add = (a, b) => a + b;
. - It reduces the potential for syntax errors by clearly differentiating the arrow function’s parameters and its body, which can be especially beneficial for developers new to ES6 syntax or when quickly scanning through code.
- By allowing configuration to enforce or disallow spaces before and after the arrow, it provides flexibility to align with various coding standards or stylistic preferences, catering to diverse team or project needs.
- Automatic fixable functionality is included, where spacing issues can be corrected automatically by ESLint, saving time during code reviews and reducing manual effort in adhering to stylistic rules.
Enforce the use of variables within the scope they are defined
function printNumbers() {
for(var i = 0; i < 5; i++) {
console.log("Number: " + i);
}
console.log("Last Number: " + i); // i is accessible here, which is not recommended
}
printNumbers();
- Ensures variables are only accessible within their defined block scope, preventing them from being mistakenly accessed or modified from outside their intended context, as illustrated in the provided “bad” example where variable
i
is accessed outside the loop. - Promotes the use of block-scoped variables (
let
andconst
) over function-scopedvar
, aligning with modern JavaScript best practices and helping to avoid common pitfalls associated withvar
’s function scope. - Helps maintain cleaner, more readable code by clearly defining where variables are active and relevant. This clarity can lead to easier debugging and understanding of the code flow, especially in cases with complex or nested scopes.
- Prevents potential runtime errors and logic bugs that can arise from unintentionally accessing variables outside their defined scope. For instance, accessing
i
outside its loop could lead to unexpected behaviors or errors ifi
was inadvertently changed elsewhere.
Disallow or enforce spaces inside of blocks after opening block and before closing block
if(true){console.log('Hello, world!');}
- This ESLint rule ensures consistency in how blocks are spaced, which can significantly improve code readability and maintainability. By enforcing or disallowing spaces after opening and before closing blocks, the code becomes easier to scan visually, helping developers quickly understand the structure and flow of the code.
- It provides flexibility for different coding styles by allowing configuration to either always require spaces inside blocks or never allow them. This means teams can adopt the style that best suits their preferences while still ensuring uniformity across the project.
- The rule includes logic to handle different types of blocks, including
BlockStatement
,StaticBlock
, andSwitchStatement
, 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. - The rule offers auto-fixing capabilities, which can save developers time by automatically adjusting the spacing inside blocks according to the configured preference (adding or removing spaces as needed). This feature can be particularly useful during code refactoring or when applying the rule to an existing codebase, as it helps align all code with the preferred style without manual intervention.
Enforce consistent brace style for blocks
if (condition)
{
executeFunction();
}
else
{
executeAnotherFunction();
}
- Ensures readability and consistency across the codebase by enforcing a specific brace style for blocks, which makes it easier for developers to understand and navigate the code, especially in larger projects where consistency matters for maintenance and collaboration.
- Minimizes the potential for syntax errors and reduces debug time by automatically fixing misplaced braces, which can prevent runtime errors that are hard to trace back to formatting issues.
- Supports different coding styles (e.g., “1tbs” or “allman”) to accommodate team preferences or project standards, allowing for flexibility in adhering to widely accepted coding conventions or company-specific guidelines.
- Improves collaboration among team members who may have diverse coding habits by standardizing block formatting, leading to cleaner merge requests and fewer conflicts related to code style during the development process.
Require return
statements after callbacks
function processData(error, data, callback) {
if (error) {
console.error("An error occurred:", error);
callback(error);
}
// some data processing
console.log("Processing data:", data);
}
- Ensures consistency in handling callback functions, by enforcing a pattern where callbacks are immediately followed by a return statement, thus preventing the inadvertent execution of code following the callback invocation.
- Helps prevent common errors associated with asynchronous code, like a function inadvertently continuing execution after a callback has been called, which could lead to unexpected behavior or hard to trace bugs.
- Improves readability and maintainability of the code by making the control flow clearer, especially in scenarios involving error handling or early function exits.
- Encourages best practices in asynchronous programming by implicitly promoting the early termination of function execution upon the completion of the required asynchronous action, thereby making the code more robust and easier to understand.
Enforce camelcase naming convention
let user_id = 1;
function get_user_info(userID) {
// other logic
}
const product_info = {
product_id: 123,
product_name: "Widget"
};
const api_data = {
API_KEY: "XYZ",
api_url: "https://api.example.com"
}
-
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.
Enforce or disallow capitalization of the first letter of a comment
function calculateArea(radius) {
const area = Math.PI * radius * radius;
// calculate area of the circle
console.log(area);
// returning the result
return area;
}
- The rule focuses on improving the readability and professionalism of code comments by enforcing or disallowing capitalization, which contributes to maintaining a consistent style across the codebase, making the comments visually clear and easier to follow.
- It provides configurable options, allowing teams to adapt the rule based on their specific style guidelines (e.g., always capitalize, never capitalize, ignore certain patterns), thus accommodating a variety of coding conventions and preferences.
- The rule includes logic to intelligently ignore URLs, inline comments, consecutive comments, and comments with default or custom ignore patterns, ensuring that the enforcement of capitalization does not apply too rigidly where it doesn’t make sense or might disrupt the intended meaning.
- It offers automatic fix functionality, which can correct non-compliant comments by capitalizing or decapitalizing the first letter as needed. This feature can save developers time and effort during the code review and editing process by automating stylistic corrections.
Enforce that class methods utilize this
class MyClass {
static myStaticMethod() {
console.log("This is a static method.");
}
myMethod() {
console.log("This method does not use 'this'.");
}
}
- Enforces that class methods, which are intended to interact with instances of the class, make use of the
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. - Provides a configuration option to exclude specific methods by name from the rule enforcement, allowing developers to selectively apply this rule to only the methods where it makes sense, thus offering flexibility in adopting code style practices.
- Supports the checking of class fields defined using the newer JavaScript syntax for class fields, making it relevant for modern JavaScript codebases that take advantage of the latest ECMAScript features for cleaner and more concise class definitions.
- Automatically exempts static methods and constructor methods from this check, recognizing that these types of methods either do not operate on a class instance (
static
methods) or have special roles in class behavior (constructors), which might not necessitate the use ofthis
. This built-in exemption reduces false positives and focuses the rule on standard instance methods wherethis
is expected to be used.
Require or disallow trailing commas
const obj = {
name: "John",
age: 30
};
function example(
param1,
param2
) {}
const arr = [
"apple",
"banana"
];
-
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.
Enforce consistent spacing before and after commas
const numbers = [1,2 , 3 ,4,5];
const obj = {first:'John',last: 'Doe' ,age: 50};
- The rule enhances code readability and maintainability by enforcing a consistent spacing style around commas, making the code more uniform and easier to follow for developers who may be working on the project.
- It helps prevent syntax and parsing errors that could arise from inconsistent spacing around commas, which could be particularly beneficial in complex arrays or objects, improving the overall code quality.
- The rule’s automatic fix ability can save developers time on formatting and make it easier to adhere to coding standards without manual intervention, allowing them to focus more on logic and problem-solving.
- By providing options to configure spacing before and after commas, it offers flexibility to adapt to various coding style guides or personal preferences, promoting a user-friendly coding environment that can cater to different teams or projects.
Enforce consistent comma style
const array = [
1
, 2
, 3
];
const obj = {
one: 1
, two: 2
, three: 3
};
function foo(a
, b
, c) {
console.log(a, b, c);
}
-
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.
Enforce a maximum cyclomatic complexity allowed in a program
function checkUserAccess(user) {
if (user.role === 'admin') {
if (user.age > 18) {
if (user.status === 'active') {
// Additional nested conditions...
if (user.experience > 5) {
if (user.location === 'remote') {
// ...
}
}
}
}
} else if (user.role === 'moderator') {
// ...
}
// Various other conditions increasing the complexity
}
- The given ESLint rule emphasizes the importance of maintaining a manageable cyclomatic complexity within a program by enforcing a maximum threshold. This is critical for preventing software from becoming overly complex and hard to maintain, illustrating the rule’s focus on promoting maintainability and readability in the codebase.
- By offering a configuration option to set a custom threshold, the rule provides flexibility, allowing development teams to tailor the complexity limit based on the specific needs and standards of their projects. This adaptability ensures that teams can enforce a complexity standard that aligns with their coding practices and application requirements.
- The rule’s method of incrementally tracking complexity through various control flow paths—such as loops and conditional statements—helps developers identify and refactor parts of the code that contribute to high complexity. This targeted approach facilitates the reduction of complexity at its source, encouraging the use of simpler, more understandable code structures.
- Generating specific reports when complexity exceeds the predefined threshold serves as an immediate feedback mechanism for developers. This not only helps in identifying complex code areas in need of refactoring but also educates developers about the impact of certain code constructs on overall complexity. This educational aspect of the rule can lead to better coding habits over time, as developers become more aware of the complexities introduced by their code.
Enforce consistent spacing inside computed property brackets
const myObject = { 'a key': 'value' };
const keyName = 'a key';
console.log(myObject[ keyName ]);
-
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.
Require return
statements to either always or never specify values
function getItem(condition) {
if (condition) {
return { name: 'Item Name' };
}
// Implicitly returns `undefined` because there is no return statement here.
}
- The rule checks for consistency in return statements within functions, ensuring that they either always return a value or never do. This can prevent misunderstandings about what a function is expected to return, leading to fewer bugs related to unexpected return types.
- By enforcing a consistent return policy, the rule can catch potential errors early in the development process, such as when a developer accidentally omits a return statement in one execution path of a function, which might lead to undefined behavior or type errors at runtime.
- The option
treatUndefinedAsUnspecified
allows for flexibility in treating returns that explicitly returnundefined
as unspecified, accommodating different coding styles while still enforcing overall consistency in the codebase, which can be beneficial in projects with multiple contributors. - It provides clear feedback on where and why the code is inconsistent regarding return values, by reporting the exact location and nature of the inconsistency. This can significantly aid in debugging and maintaining code, especially as projects grow in size and complexity.
Enforce consistent naming when capturing the current execution context
function myFunction() {
var self = this; // 'self' used as an alias for 'this'
setTimeout(function() {
console.log(self);
}, 1000);
var that = this; // 'that' also used as an alias for 'this'
setTimeout(function() {
console.log(that);
}, 2000);
}
- Ensures that when 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. - Helps to prevent bugs that can arise from incorrectly assigning or using an alias that was intended to capture
this
, but instead is either not assigned or assigned to a different value. - Facilitates easier code maintenance and refactoring by enforcing a clear and predictable pattern for referencing the current execution context in various scopes, making it simpler to understand and modify existing code.
- Improves codebase uniformity and adherence to team or project coding standards regarding the handling of
this
, promoting more organized and professional code practices.
Require super()
calls in constructors
class DerivedClass extends BaseClass {
constructor() {
// No super() call.
this.name = 'Derived';
}
}
-
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 thatsuper()
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.
Enforce consistent brace style for all control statements
if (user.isActive)
console.log('User is active');
- Prevents potential block scope confusion by enforcing curly braces, making it explicit when a new block begins and ends. This helps avoid bugs that might arise when adding new statements to an existing control structure without properly enclosing them in braces.
- Improves readability and maintainability of the code by enforcing a consistent brace style. This consistency helps developers quickly understand the structure of control statements, especially in complex codebases or when switching between different projects with similar coding styles.
- Aids in reducing syntax errors, particularly in edge cases involving automatic semicolon insertion (ASI). Enforcing braces ensures that there is no ambiguity that could lead to unexpected ASI behavior, which could otherwise introduce silent errors into the code.
- Supports various configuration options (
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.
Enforce default clauses in switch statements to be last
switch (expression) {
case 1:
// Code to execute if expression === 1
break;
default:
// Code to execute if expression doesn't match any case
break;
case 2:
// Code to execute if expression === 2
break;
}
- Ensuring the
default
clause is last improves the readability ofswitch
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. - It helps in avoiding logical errors that might occur from mistakenly placing cases after the
default
clause, which could lead to unexpected behavior if developers assume all case clauses are evaluated before thedefault
. - Streamlining the position of the
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 thedefault
, potentially causing unreachable code. - This rule assists in maintaining a uniform codebase, especially in larger projects or teams, by enforcing a standardized approach to organizing
switch
statements, which can improve the efficiency of code reviews and onboarding new team members.
Require default
cases in switch
statements
function getFruitColor(fruit) {
switch (fruit) {
case 'apple':
return 'red';
case 'banana':
return 'yellow';
// No default case
}
}
- Ensures comprehensive error handling in
switch
statements by requiring adefault
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. - Promotes best coding practices and code maintainability. By mandating a
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. - Enhances readability and intent clarity for future code maintainers or reviewers by explicitly showcasing the consideration for all possible values, including those not explicitly listed in the
switch
cases. Including adefault
case or an explanatory comment where adefault
case might be intentionally omitted serves as documentation within the code itself. - Allows for customizable enforcement through the optional
commentPattern
option, providing teams flexibility in adhering to the rule while accommodating cases where adefault
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 adefault
case is a deliberate choice supported by comments that match the provided pattern.
Enforce default parameters to be last
function greet(message, name = 'World') {
console.log(message + ', ' + name + '!');
}
-
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.
Enforce consistent newlines before and after dots
const person = {firstName: "John", lastName: "Doe"};
const fullName = person
.firstName + " " + person
.lastName;
- Enforcing a specific placement for the dot in member expressions (either before the property or after the object) promotes code readability and consistency. This rule ensures that team members follow a unified syntax style, making the codebase easier to understand and maintain.
- The rule provides automatic fix suggestions, which can streamline the development process by reducing the need for manual corrections. Developers can apply these suggestions to quickly conform to the chosen dot location style without spending time on minor formatting issues.
- By setting a clear expectation for dot positioning, this rule can help prevent syntax errors that might arise from misunderstanding the association between the object and its properties, especially for those new to JavaScript or coming from languages with different member access syntaxes.
- The configurable nature of the rule allows teams to align the enforcement with their specific coding standards or preferences (“object” or “property”), offering flexibility while still maintaining a level of enforced consistency. This can be particularly beneficial in diverse teams or projects that integrate code from multiple sources with varying stylistic preferences.
Enforce dot notation whenever possible
const user = {
name: 'John Doe',
age: 30
};
// Using bracket notation unnecessarily
const userName = user['name'];
const userAge = user['age'];
-
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
thanobject['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.
Require or disallow newline at the end of files
const message = "Hello, world!";
console.log(message);
- Enforces a consistent file ending, which can help in minimizing diffs. Files without a newline at the end can create unnecessary diff lines when new lines of code are added, making version control histories cleaner and easier to follow.
- Improves compatibility across different systems and editors. Some Unix-based systems may have issues or behave unexpectedly if files don’t end with a newline. This rule helps ensure files are compatible regardless of the environment they’re being used in.
- Provides automatic fix options, reducing manual effort for developers. Depending on the configuration (always, never, unix, windows), it can automatically add or remove the newline at the end of files, streamlining code formatting processes without requiring developers to manually adjust each file.
- Supports customizable EOL characters (LF for Linux/Unix/macOS, CRLF for Windows) to comply with different operating system conventions. This flexibility allows projects to enforce a consistent EOL character across all platforms, ensuring that the codebase remains uniform and avoiding potential issues with line endings in version control systems.
Require the use of ===
and !==
if (userType == "admin") {
console.log("User is an admin.");
}
-
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 andnull
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.
Enforce “for” loop update clause moving the counter in the right direction
// Incorrect loop direction, potentially leading to an infinite loop
for (let i = 10; i >= 0; i++) {
console.log(i);
}
-
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.
Require or disallow spacing between function identifiers and their invocations
// Bad code with unnecessary space when "never" is expected
function greet () {
console.log('Hello, world!');
}
greet ();
- This rule enforces a consistent spacing style between function names and their invocations, which can improve code readability and maintain a consistent style across the codebase. Developers won’t have to guess or debate the placement of spaces in function calls, leading to more uniform code.
- The rule provides an option to allow or disallow newlines between function names and their invocations, which offers flexibility for different code styling preferences. This means that teams can adapt the rule based on their specific project guidelines or personal preferences, ensuring that even when allowing for line breaks, the code remains consistent with the team’s standards.
- It includes automatic fixing capabilities that can automatically adjust spacing or remove newlines according to the set configuration. This automation can save time during code reviews and reduce manual effort required to conform to style guidelines, potentially speeding up the development process.
- The rule takes into consideration the presence of comments and conditional (optional) chaining syntax to avoid creating unintended syntax errors when automatically fixing spacing issues. This careful handling ensures that automatic fixes do not introduce bugs or alter the logic of the code, maintaining code integrity while still enforcing style rules.
Require function names to match the name of the variable or property to which they are assigned
// Example 1: Variable assignment mismatch
const myFunc = function anotherFuncName() {};
// Example 2: Object property mismatch
const obj = {
myMethod: function anotherMethodName() {}
};
// Example 3: Exported function mismatch (CommonJS pattern)
module.exports = {
exportedFunc: function differentName() {}
};
-
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.
Require or disallow named function
expressions
const data = [1, 2, 3];
const doubled = data.map(function (item) {
return item * 2;
});
-
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.
Enforce the consistent use of either function
declarations or expressions
// Bad: Using a function expression when the ESLint rule prefers function declarations
var add = function(x, y) {
return x + y;
};
-
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 howthis
is used. This is particularly useful for older JavaScript where arrow functions and their lexicalthis
binding aren’t available, ensuring that functions are defined in a style that best suits their usage context and the surrounding lexical scope.
Enforce line breaks between arguments of a function call
myFunction(arg1, arg2, arg3);
- Enhances code readability by ensuring that each argument of a function call is on its own line, especially in cases where there are multiple arguments, making it easier to scan and understand each individual argument.
- Reduces merge conflict potential in distributed version control systems by structurally organising arguments on separate lines, making it clearer which lines have been altered and potentially reducing the scope of conflicts when merging code changes.
- Facilitates more meaningful diffs during code reviews or when examining version history, as changes to the arguments of function calls are isolated to specific lines, making it easier to identify what was added, removed, or altered.
- Aids in maintaining consistency across the codebase regarding the formatting of function calls, especially in collaborative projects, by enforcing a specific style guideline (line breaks between arguments), thus reducing stylistic discrepancies that can lead to cluttered or inconsistent code formatting practices.
Enforce consistent line breaks inside function parentheses
// Example that could violate the given ESLint rule based on configuration
const result = someFunction(param1, param2, param3);
- Enhances readability by ensuring consistent formatting within function parentheses which can be particularly beneficial in functions with multiple parameters or arguments, making it easier to discern individual elements at a glance.
- Provides an option for enforcing line breaks based on the number of arguments (
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. - Supports multiple configurations (e.g.,
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. - Automatically corrects violations by inserting or removing newlines as needed, reducing manual effort required in code reviews and helping maintain code quality standards with minimal intervention, which can significantly speed up the development process and reduce potential for human error.
Enforce consistent spacing around *
operators in generator functions
// Bad - No space before or after '*'
function*generator() {
yield 'Hello world!';
}
// Bad - Space before '*' only
function * generator() {
yield 'Hello again!';
}
// Bad - No space after '*'
function*generatorAgain() {
yield 'And hello once more!';
}
- Enforces a consistent coding style regarding spacing around the
*
in generator functions, which can improve code readability and maintainability by adhering to a project’s or team’s coding standards. - Provides flexibility in styling preferences by supporting configuration for spaces before, after, both, or neither side of the
*
, catering to different team or project style guidelines without enforcing a single style. - Includes auto-fixing capabilities, allowing developers to automatically correct styling issues without manual intervention, thereby saving time and reducing the likelihood of human error during code formatting.
- Specifically targets generator functions, allowing other function types or operators in the codebase to follow different spacing conventions without interference, thus focusing on a particular aspect of JavaScript syntax to maintain clarity and specificity in code styling rules.
Enforce return
statements in getters
const person = {
firstName: "John",
lastName: "Doe",
get fullName() {
console.log(`${this.firstName} ${this.lastName}`);
// Missing return statement
}
};
-
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.
Require require()
calls to be placed at top-level module scope
function loadDependency() {
if (condition) {
const fs = require('fs');
// Other logic using fs module
}
}
- Prevents inconsistent require() placements, ensuring all
require()
calls are at the top level, making it easier to locate dependencies and understand the module’s dependencies at a glance. - Facilitates better static analysis by tools and improves predictability in module loading, particularly important in environments where module loading order affects initialization and use.
- Helps in maintaining a cleaner and more organized code structure, where dependencies are declared upfront, reducing the cognitive load for developers when navigating and understanding the codebase.
- Reduces runtime overhead and potential errors related to conditional or repeated
require()
calls by establishing a pattern where modules are loaded once at the beginning, improving the performance and reliability of the application.
Require grouped accessor pairs in object literals and classes
class Person {
constructor(name) {
this._name = name;
}
set name(newName) {
this._name = newName;
}
// Some other methods...
doSomething() {}
get name() {
return this._name;
}
}
- Enforces code consistency by requiring that accessor pairs within object literals and classes (getters and setters) are grouped together, which can make the code easier to read and understand, especially in large classes or objects with many properties.
- Helps to avoid potential runtime errors or confusing bugs by making sure that related accessors (getters/setters) are defined close to each other, which can reduce the chance of mistakenly editing or calling the wrong accessor method.
- Supports configurable order (“getBeforeSet” or “setBeforeGet”) to align with team’s coding standards or personal preferences, ensuring that all team members follow the same order and contributing to code uniformity across the project.
- By automatically reporting ungrouped or incorrectly ordered accessor pairs, it assists in maintaining code quality during code reviews and reduces the need for manual checks related to accessor organization, saving time and effort for developers.
Require for-in
loops to include an if
statement
var obj = { a: 1, b: 2, c: 3 };
for (var prop in obj) {
console.log("obj." + prop + " = " + obj[prop]);
}
-
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 anif
statement, such asif (obj.hasOwnProperty(prop))
, to check if the property belongs to the object directly. -
By enforcing an
if
statement insidefor-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.
Require error handling in callbacks
fs.readFile('somefile.txt', function(err, data) {
if (data) {
console.log('File data:', data);
}
});
- The rule specifically targets the common practice in Node.js and JavaScript where callbacks include an error parameter conventionally named
err
. By enforcing an inspection of thiserr
parameter, it helps ensure that asynchronous operations are robustly designed to handle failures, which are common in I/O operations or network requests. - This rule is configurable, allowing for the detection of error parameters that may not be named
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. - By activating this rule, it encourages the development of error-aware code. This is crucial in Node.js environments or in any asynchronous JavaScript code, where unhandled errors can lead to crashes or unpredictable behavior. It promotes the practice of early error detection and handling, which can simplify debugging and improve the reliability of applications.
- The rule potentially reduces the risk associated with uncaught exceptions by reminding developers to handle errors at their source. This can lead to improved application stability and a better user experience, as errors can be gracefully managed and communicated to the user, rather than leading to sudden application failures.
Disallow specified identifiers
let data = fetchUserInfo();
console.log(data);
- This rule prevents the use of specific identifier names that may be deemed inappropriate, potentially confusing, or could collide with names of global objects or reserved keywords, enhancing code clarity and maintainability by encouraging the use of more descriptive and unique names.
- By incorporating a denylist within its logic, it enables a customizable approach to enforcing naming conventions across a codebase, allowing project-specific or company-wide standards on identifier names to be easily implemented and adhered to.
- The rule’s logic includes checks for whether an identifier is being used in a context that suggests modification or creation of a property, versus purely accessing a property, distinguishing between potentially harmful naming practices versus necessary accesses of properties with restricted names on objects outside of the user’s control.
- It optimizes performance and avoids reporting duplicates by utilizing a
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.
Disallow specified identifiers
// Imagine 'data' is specified in the denylist
function processData(data) {
console.log(data);
}
const data = { key: 'value' };
processData(data);
- Helps maintain a consistent naming convention across the codebase by disallowing specific identifiers that might be deemed inappropriate or confusing, ensuring that developers choose more descriptive or suitable names.
- Aids in preventing the accidental use of global variables or reserved keywords that could lead to runtime errors or conflicts within the code, by checking references to global variables and ensuring they are declared in the source code.
- Enhances code readability and maintainability by encouraging the use of names that clearly reflect the intent of the variable or function, instead of using generic or potentially misleading identifiers.
- Supports a customizable and adaptable codebase by allowing teams to define their own denylist of identifiers based on project or company standards, making it easier to enforce specific naming conventions and prevent undesired practices.
Enforce minimum and maximum identifier lengths
let a = 10; // Variable name "a" is too short.
const b = (c) => { // "b" and "c" are also too short.
let d = c + 2; // "d" is too short too.
return d;
};
- The rule enforces minimum and maximum lengths for identifiers, which promotes the use of more descriptive names. This can make the code more readable and understandable for developers, reducing the cognitive load when interpreting the purpose of variables, functions, etc.
- It includes the flexibility to define exceptions and exception patterns for identifier names that might not conform to the standard length requirements but are still considered acceptable. This allows for the rule to be adapted to project-specific conventions or naming practices that may have legitimate reasons for shorter or longer names.
- The rule’s consideration for different contexts where an identifier can be used (e.g., properties, variable declarations, function names) ensures a comprehensive enforcement across the codebase. This consistency in naming practices helps in maintaining a uniform code style, making it easier for teams to collaborate.
- By providing specific messages for identifiers that are too short or too long, the rule helps developers understand exactly why their code does not meet the standards. This immediate feedback can aid in the learning process, encouraging developers to choose more appropriate names without having to guess what the exact issue is.
Require identifiers to match a specified regular expression
// This code does not adhere to a common naming convention, such as camelCase.
const user_data = { userID: 123, userName: 'JohnDoe' };
function fetch_user_info() {
return user_data;
}
- Ensures consistency in the naming conventions across your codebase by requiring identifiers to match a specified regular expression. This can enforce a standard naming convention such as camelCase or snake_case, depending on the configured pattern, which makes the code easier to read and maintain.
- Helps in avoiding potential conflicts and errors in code by flagging identifiers that do not comply with the specified naming pattern. This can be particularly useful in large projects where inconsistent naming can lead to confusion about variable, function, and class names.
- Provides configuration options to tailor the rule’s behavior to specific project needs, such as whether to check properties, class fields, only declarations, and whether to ignore destructuring. This flexibility allows teams to enforce naming conventions in the areas of their codebase that matter most to them while avoiding unnecessary noise.
- Enhances code readability and maintainability by encouraging developers to use meaningful and descriptive names within the constraints of the defined naming convention. This can lead to more intuitive code, making it easier for new developers to understand the project and for the team to keep the codebase clean and organized.
Enforce the location of arrow function bodies
const fetchData = () =>
fetch('https://api.example.com/data')
.then(response => response.json());
- Promotes code consistency by enforcing a specific placement for arrow function bodies, making it easier to read and understand the code, especially for teams where multiple individuals contribute to the same codebase.
- Reduces cognitive load for developers by standardizing the format of arrow functions, whether they are placed beside the arrow or below it, thus making the codebase more predictable and easier to navigate.
- Helps in maintaining a clean and organized code structure by automatically fixing misplaced arrow function bodies with the provided auto-fix option, thereby saving time during both development and code reviews.
- Prevents potential syntax or parsing errors that might arise from unconventional arrow function body placements, ensuring the code is executed as intended without unexpected behaviors.
Enforce consistent indentation
function test() {
console.log('Hello, world!');
if (true) {
console.log('True block');
}
}
- This rule allows for flexible configurations catering to different coding styles like variable declaration, function arguments, and member expression indentation, ensuring readability across various sections of code.
- It incorporates a detailed error reporting system that not just highlights the indentation issue but also suggests the expected indentation style (spaces/tabs) and count, making it easier for developers to understand and fix the issues.
- By excluding lines that contain both spaces and tabs from reporting (to avoid conflict with the
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. - The rule handles special cases like IIFEs, blockless statements, and multi-line variable declarations, ensuring that the indentation logic is accurately applied to different JavaScript syntax structures, promoting code clarity, and maintainability.
Enforce consistent indentation
function testIndentation() {
const a = 1;
const b = 2;
if (a === b) {
console.log("This is badly indented.");
}
}
- Ensures consistency in code indentation within a project, which improves readability and maintainability.
- Allows customizable indentation settings (spaces or tabs and their respective counts) to suit different coding standards or preferences.
- Automatically identifies and reports indentation errors, reducing manual code review efforts and potential human oversight.
- Provides automatic fixing capabilities for indentation errors, streamlining the code formatting process and saving development time.
function getItem(index) {
return {
'name': 'item',
'index': index
};
}
- The ESLint rule encourages the use of ES6 object property shorthand, making the code more concise and easier to read by omitting the property name when it matches the variable name.
- By adhering to this rule, developers are reminded to use consistent coding standards when defining object properties, promoting more uniform code across the project and making it easier for other developers to understand and maintain.
- Implementing this rule helps in catching and correcting unnecessary verbosity in object creation, which can lead to reduced file sizes and potentially improve script loading times in web development scenarios.
- It educates new developers or those transitioning from older JavaScript versions about modern JavaScript features, encouraging them to adopt and get comfortable with ES6+ syntax and best practices.
Require or disallow initialization in variable declarations
// Assuming ESLint rule init-declarations is configured to "always"
let x;
const y;
for (let i; i < 10; i++) {
console.log(i);
}
- Enforces a consistent coding style where variable declarations are either always initialized at the point of declaration or never initialized, improving code readability and maintainability. This helps in understanding whether a variable is supposed to have an initial value, making the code easier to reason about.
- Helps in preventing potential run-time errors by ensuring that variables are not left unintentionally uninitialized, particularly important in languages like JavaScript where variables can be hoisted and accessed before actual initialization, potentially leading to
undefined
values. - Allows for exceptions within for loops with the
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. - Encourages developers to make conscious decisions about variable initialization, which can lead to better memory management and performance optimization, especially in scenarios where default initialization could have unintended consequences or where delayed initialization is preferred for resources.
Enforce the consistent use of either double or single quotes in JSX attributes
const MyComponent = () => {
return <div className='my-class'>Content</div>;
};
-
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.
Enforce consistent spacing between keys and values in object literal properties
const badObject = {
first: 'value1',
second :'value2',
third :'value3'
};
-
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.
Enforce consistent spacing before and after keywords
if(someCondition){
//^^ No space after 'if', and before '{'
doSomething();
}else{
//^^ No space after '}', before 'else', and after 'else'
doSomethingElse();
}
- It ensures consistency in code formatting by enforcing or disallowing spaces before and after keywords, making the code easier to read and understand.
- The rule can automatically fix spacing issues, reducing manual efforts in code reviews and allowing developers to focus on more critical aspects of code quality.
- By outlining clear expectations for spacing around keywords, it helps avoid syntax errors or bugs that could arise from incorrect spacing, especially in minified code.
- It offers configurability to cater to different coding styles or project-specific guidelines, allowing teams to maintain a uniform coding standard across the codebase.
Enforce position of line comments
const x = 5; // This assigns 5 to x
- The rule helps in maintaining readability and consistency across the codebase by enforcing a uniform position for line comments, either above the code line or beside it. This makes the code easier to read and understand, especially for new team members or when revisiting older code.
- By allowing customization through options like
position
,ignorePattern
, andapplyDefaultIgnorePatterns
, 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. - The rule can prevent potential misinterpretations of the code by making sure comments are placed in a position that clearly associates them with the corresponding line of code. For instance, placing a comment above the line it describes can help avoid ambiguity about which line of code the comment refers to, especially in complex code structures.
- It includes considerations for automatically ignored patterns and fall-through comments, recognizing common use cases where enforcing a comment position might not be practical or necessary. This thoughtful inclusion ensures that the rule is not overly restrictive and can adapt to real-world coding practices, such as ignoring auto-generated comments or specific keywords.
Enforce consistent linebreak style
function sayHello() {\r
console.log("Hello, world!");\r
}\r
sayHello();
- Ensures codebase uniformity by enforcing a consistent linebreak style, either Unix-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. - Mitigates issues related to cross-platform development where different operating systems handle linebreaks differently, thus preventing potential bugs or inconsistencies when the code is executed or edited on different platforms.
- Automates the correction process for linebreak inconsistencies, as the rule not only identifies discrepancies but also provides a fix function. This automation saves developers time and effort by not having to manually correct linebreak styles across the codebase.
- Enhances readability and maintainability of the code by keeping the stylistic aspect of the codebase consistent. This consistency is particularly beneficial for teams, ensuring that all contributors adhere to the same code formatting guidelines without having to enforce these guidelines manually.
Require empty lines around comments
function calculateSum(a, b) {
// This function calculates the sum of two numbers
return a + b;
}
-
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.
Require or disallow newlines around directives
function doSomething() {
"use strict"
let a = 2;
return a;
}
- Ensures consistency in code formatting by requiring or disallowing newlines around directive sequences, aiding in readability and maintainability of the code by creating a uniform appearance.
- Helps in delineating directive prologues from the rest of the code block, making it visually easier to distinguish between the directive part and the code logic, improving code scan-ability.
- Prevents potential errors in directive processing by clearly separating directives from the code, ensuring that they are recognized and applied correctly by JavaScript engines.
- Facilitates easier code review and maintenance by enforcing a coding standard regarding the placement of directives, thus reducing the cognitive load required to understand the structure and flow of the code.
Require or disallow an empty line between class members
class MyClass {
constructor(value) {
this.value = value;
}
getValue() {
return this.value;
}
setValue(value) {
this.value = value;
}
}
- Enhances readability of class structures by ensuring consistent spacing between class members, making it easier for developers to visually separate and identify class members.
- Supports configurable options to enforce either the presence or absence of empty lines between class members according to the project’s coding standards, promoting a unified code style within a team or project.
- Offers an exception for single-line member declarations, allowing teams to decide whether an empty line is required after single-line members, thus providing flexibility to accommodate different styling preferences for compact class definitions.
- Includes automatic fix capabilities to correct spacing issues between class members, reducing manual labor in code reviews and maintaining code quality without additional developer effort.
Require or disallow logical assignment operator shorthand
// Assuming foo and bar are defined earlier in the code
if (!foo) {
foo = bar;
}
// Another example
if (baz === undefined) {
baz = qux;
}
-
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;
versusfoo ||= 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.
Enforce a maximum number of classes per file
// Assuming the rule is configured to allow only one class per file...
class Dog {
constructor(name) {
this.name = name;
}
bark() {
return `${this.name} says woof`;
}
}
class Cat {
constructor(name) {
this.name = name;
}
meow() {
return `${this.name} says meow`;
}
}
-
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.
Enforce a maximum depth that blocks can be nested
function deeplyNestedFunction() {
if (true) { // 1st level
for (let i = 0; i < 10; i++) { // 2nd level
while (i < 5) { // 3rd level
if (i % 2 === 0) { // 4th level
try { // 5th level
// Some logic here
} catch (error) {
console.error(error);
}
}
}
}
}
}
- This rule helps in maintaining a readable and maintainable codebase by enforcing a maximum nesting depth for blocks, making it easier for developers to understand the logic without getting lost in deeply nested structures.
- By setting a limit on the complexity of functions through block depth, the rule indirectly encourages more modular code design. Developers are prompted to refactor deeply nested blocks into separate functions or modules, enhancing code reuse and testability.
- The rule assists in identifying potential areas in the code that are overly complicated and therefore more prone to errors. By keeping the nesting levels within a set limit, the cognitive load on understanding the code decreases, which can lead to fewer logical errors and bugs.
- It increases the potential for code optimization by the compiler or interpreter. Simplified code structures that avoid deep nesting are often easier for compilers to optimize, potentially leading to performance improvements in the execution of the code.
Enforce a maximum line length
const errorMessage = "This is a really long error message that exceeds the maximum line length set by the ESLint rule for maximum length of a line in a JavaScript or TypeScript file.";
console.log(errorMessage);
- The rule includes a sophisticated method for computing the length of lines that contain tabs, adjusting based on the set tab width within the options. This is crucial for accurately enforcing line length in codebases that use tabs for indentation, ensuring the line length check remains consistent regardless of the viewer’s tab setting preferences.
- It provides options to ignore certain content types within lines, such as URLs, strings, template literals, and regular expression literals. This feature is important in cases where excluding these types from the line length count can prevent unnecessary segmentation of lines that contain long literals or URLs, which could make code less readable if broken up.
- The rule can be configured to either include or exclude comments when calculating line lengths, offering flexibility. For projects where comments need to be concise or could be more permissive in length compared to code, this helps maintain readability and adherence to documentation standards without overly restrictive measures.
- The ability to specify a custom pattern to ignore via
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.
Enforce a maximum number of lines of code in a function
function processData(data) {
// Initialize variables
let result = [];
let tempData = data.filter(item => item.isActive);
// Perform some complex data manipulation
tempData.forEach(item => {
let modifiedItem = {
...item,
timestamp: new Date().toISOString(),
isValid: true
};
// More complex logic here, potentially spanning many lines
result.push(modifiedItem);
});
// Further manipulation and processing
result = result.map(item => {
// Assume more extensive logic here
return item;
});
// Assume more code here performing various tasks
console.log("Processing completed.");
return result;
}
- The rule encourages writing concise functions by enforcing a maximum number of lines, which improves readability. Longer functions can be harder to follow, making it more difficult to understand the logic and flow of the code.
- By imposing a limit on the number of lines per function, developers are prompted to refactor large functions into smaller, more manageable pieces. This practice promotes code modularity, making the codebase more maintainable and easier to debug.
- The rule’s options to skip comments and blank lines when counting lines allow for flexibility in coding style. This means that developers can still have comprehensive comments and whitespace for code clarity without affecting the enforcement of the rule.
- The inclusion of an option to ignore Immediately Invoked Function Expressions (IIFEs) caters to specific coding patterns where functions are defined and executed simultaneously, thus not unfairly penalizing this pattern for its typically compact syntax despite potentially high logic density.
Enforce a maximum number of lines per file
// File: myOverlyLongScript.js
// Description: This file exceeds the maximum allowed number of lines.
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
// Imagine here more than 300 similar small utility functions making this file longer than the allowed max line count
// The final line that exceeds the limit
console.log("This file is too long!");
- This ESLint rule enforces a maximum number of lines per file, which can help developers maintain readability and manageability of code files. By keeping files under a specified line count, the code is more likely to remain organized and clear, facilitating easier navigation and understanding for anyone working on or reviewing the project.
- The rule’s flexibility in configuration (allowing for the exclusion of comments and blank lines from the line count) caters to various coding styles and preferences. This ensures that the enforcement of the rule does not unnecessarily hinder the utilization of comments for documentation or the use of blank lines for code separation, which are both common practices intended to improve code readability.
- By enforcing a maximum number of lines, this rule subtly encourages the practice of modular programming. Developers are nudged towards dividing their code into smaller, more focused modules or components rather than having overly long files. This can lead to better code organization, easier testing, and more straightforward maintenance and updates.
- The rule provides immediate feedback to developers when the maximum line count is exceeded, allowing for prompt correction and adherence to best practices during the development process. This proactive alert can prevent the accumulation of tech debt related to unwieldy files and promote a more disciplined and quality-focused coding culture within a team or project.
Enforce a maximum depth that callbacks can be nested
// Bad: Callbacks nested more than 3 levels deep
getData(function(a) {
parseData(a, function(b) {
processData(b, function(c) {
validateData(c, function(d) { // This is the 4th level of nesting, which violates our configured rule
console.log(d);
});
});
});
});
- This rule enforces a maximum depth that callbacks can be nested, which directly contributes to improving code readability by preventing deeply nested structures that are hard to follow and understand. Deeply nested callbacks, often referred to as “callback hell,” can make code difficult to debug and maintain.
- By setting a threshold for the maximum depth of nested callbacks, it encourages developers to explore and adopt alternative approaches to asynchronous control flow, such as Promises or async/await, which lead to flatter and more readable code structures. This can help in modernizing codebases and making them more in line with current JavaScript best practices.
- The configurable threshold of the ‘max-nested-callbacks’ rule allows teams to set a specific nesting limit that aligns with their coding standards and preferences. This flexibility ensures that the rule can be adapted to different project requirements and developer experience levels, promoting a code style that is consistent and tailored to the team’s needs.
- Given the rule’s ability to immediately flag violations through ESLint’s reporting mechanism, it serves as an automated way to enforce code quality standards related to nesting depth during the development process. This immediate feedback loop helps developers learn and apply best practices in real-time, potentially reducing the need for time-consuming code reviews focused on structural issues like nesting depth.
Enforce a maximum number of parameters in function definitions
function processUserInfo(id, name, email, status, location) {
// Function implementation
}
- This rule encourages better function design by enforcing a limit on the number of parameters, which leads to functions that are easier to understand and use. Functions with too many parameters can become confusing and hard to manage, making the code less readable and maintainable.
- It promotes the use of objects for passing multiple parameters. This makes the function calls clearer because it’s easier to see what each parameter represents, as opposed to a long list of arguments where the purpose of each can become unclear.
- By limiting the number of parameters, this rule indirectly encourages developers to think more about the responsibilities of their functions. Functions doing too much can result in a high number of parameters; thus, this rule can lead to better separation of concerns and more modular code.
- It improves the testability of the code. Functions with fewer parameters are generally easier to set up in test cases. When a function takes an object as an argument instead of multiple separate parameters, it’s also easier to provide mock data for testing, as you don’t have to match the parameter list exactly in every test.
Enforce a maximum number of statements allowed per line
let a = 1; let b = 2; let c = 3;
- This rule enforces readability and maintainability by limiting the number of statements that can appear on a single line, which helps to prevent code from becoming cluttered and difficult to read.
- By setting a maximum number of statements per line, the rule encourages developers to organize their code in a way that is easier to debug. A single line with too many statements can make it hard to pinpoint errors.
- It promotes a coding style that is consistent across a project, making it easier for teams to collaborate. When all developers adhere to the same rule regarding the number of statements per line, the codebase becomes more uniform and comprehensible to everyone.
- The rule allows for exceptions in certain cases, like control statements with a single child statement, which demonstrates its flexibility in adapting to common coding practices while still enforcing overall readability and structure in the code.
Enforce a maximum number of statements allowed in function blocks
function doALotOfThings() {
let a = 1;
let b = 2;
let c = 3;
let d = 4;
// Assume max allowed statements is 10 for this example, the code below exceeds that.
let e = 5;
let f = 6;
let g = 7;
let h = 8;
let i = 9;
let j = 10;
let k = 11; // Exceeding statement
console.log(a + b + c + d + e + f + g + h + i + j + k);
}
- This rule encourages developers to write more modular code by enforcing a limit on the number of statements within a function block, thus potentially reducing the complexity of functions and making them easier to understand and maintain.
- By setting a maximum number of statements allowed in a function, it indirectly encourages the practice of breaking down large, monolithic functions into smaller, reusable pieces, leading to better code organization and potentially promoting code reuse.
- The rule allows for configuration (e.g., setting the maximum number of statements and the option to ignore top-level functions), providing flexibility to adapt the rule based on the project’s requirements or coding standards, and ensuring that it can be applied in a manner that reflects the needs of different codebases.
- The inclusion of an option to ignore top-level functions respects the fact that sometimes initialization functions or scripts that run at the program’s entry point may require a different approach and should not be penalized for having more statements, thus offering a tailored approach to enforcing code quality standards without being overly restrictive in scenarios where exceptions to the rule may be justified.
Enforce a particular style for multiline comments
// This is a comment
// that spans multiple
// lines
- By enforcing a consistent style for multiline comments, this rule helps maintain readability and uniformity across the codebase, particularly for projects with multiple contributors who may have different commenting habits.
- It supports automatic conversion between different multiline comment styles (such as converting separate line comments into a starred-block comment), making it easier for developers to conform to the project’s coding standards without manually editing comments.
- The rule includes an option to check JSDoc comments, ensuring that documentation comments follow the configured style and thus improving the overall quality and consistency of the documentation within the code.
- This rule also handles edge cases, such as ensuring that the converted comment blocks do not inadvertently close themselves or introduce syntax errors, by checking for the presence of ”*/” within the comment body and adjusting the comment style accordingly.
Enforce newlines between operands of ternary expressions
const status = age > 18 ? 'adult' : 'minor';
-
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.
Require constructor names to begin with a capital letter
function animal(name, species) {
this.name = name;
this.species = species;
}
var myPet = new animal("Fido", "Dog");
- Enforces a consistent naming convention for constructor functions by requiring them to start with a capital letter, which aids in clearly distinguishing constructors from regular functions. This helps developers quickly understand when a function is intended to be used with the
new
keyword, preventing misuse. - Improves code readability and maintainability by adhering to a widely accepted coding convention. When scanning through code, seeing a capital letter at the beginning of a function name signals to the developer that the function is a constructor, which can aid in understanding how objects of certain classes are created.
- Reduces the likelihood of runtime errors related to the incorrect use of constructors. For instance, calling a constructor function without the
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. - Supports customizable exceptions and patterns through its configuration options, allowing teams to tailor the rule to fit their specific project needs or to accommodate third-party libraries that may not follow the same naming conventions. This flexibility ensures that the rule can be applied in a manner that maximizes its benefits without hindering development with unnecessary restrictions.
Enforce or disallow parentheses when invoking a constructor with no arguments
class Person {}
// Assuming the rule is configured to always require parentheses
const person = new Person;
- Ensures consistency across the codebase regarding the invocation of constructors without arguments, reducing the cognitive load for developers by standardizing whether parentheses are required or not in these scenarios.
- Helps prevent potential errors in minified code where the lack of parentheses could lead to unexpected results, especially when constructors are used without arguments.
- Facilitates automatic code formatting and linting tools to insert or remove parentheses as needed based on the configured preference, helping developers to focus on logic rather than formatting.
- Enhances readability and clarity of the code by making explicit the instantiation of objects, especially for those coming from other programming languages where the parentheses are compulsory, thereby improving cross-language developer experience.
Require or disallow an empty line after variable declarations
function sayHello() {
var name = 'John Doe';
console.log('Hello, ' + name);
}
- The rule enforces a consistent coding style regarding the spacing after variable declarations which can help in improving code readability and maintainability. Specifically, it dictates whether there should be an empty line after declarations, making the code easier to scan through.
- This rule allows for adaptability to different team or project coding styles by offering a configurable option between “always” requiring a newline or “never” allowing back-to-back variable declarations and statements. This ensures that the rule can be tailored to fit the preferred coding standard of an individual or team.
- The rule intelligently handles edge cases such as variable declarations within for loops or export statements, and even considers different coding styles that may or may not use semicolons. This level of detail helps in avoiding unnecessary or incorrect linting warnings that could arise from less nuanced rule implementations.
- It offers automatic fix functionality, which can save developers time by automatically inserting or removing the newline based on the configured option. This is especially useful during code refactoring or when adopting the rule on an existing codebase, as it reduces the manual effort required to conform to the rule.
Require an empty line before return
statements
function exampleFunction() {
const a = 1;
if (a === 1) {
console.log("a is 1");
return a;
}
return null;
}
- Improves readability by clearly separating the
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. - Helps in maintaining a consistent code style across the project, as the presence of an empty line before
return
statements becomes a project-wide standard that all developers follow, leading to a more uniform codebase. - Minimizes the risk of merge conflicts related to stylistic differences when multiple developers are working on the same codebase, as the rule enforces a specific style that everyone adheres to.
- Aids in quickly spotting unintended
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.
Require a newline after each call in a method chain
// Bad Code: Method calls are not separated by newlines when chaining which makes it harder to read.
const result = array.map(item => item.value).filter(value => value > 10).reduce((acc, curr) => acc + curr, 0);
- Enhances code readability: This rule mandates a newline after each call in a method chain, spreading chained calls vertically rather than horizontally. This makes each step of the chain distinct and more readable, especially for complex operations or when working with long method names and arguments.
- Improves maintainability: By enforcing a consistent format for method chains, the rule aids in maintaining a uniform codebase. Should the logic within a chain need updating or debugging, it becomes easier to isolate relevant sections without wading through a dense, horizontally elongated code block.
- Facilitates easier code review: The separation of chained calls onto new lines allows for clearer code diffs during version control reviews. Reviewers can quickly identify which chain link has been modified, added, or removed without parsing a single, lengthy line of code.
- Customizability for chain length: This rule provides an option to ignore chains below a certain depth, offering flexibility. Teams or projects preferring not to enforce this rule on shorter chains can adjust the
ignoreChainWithDepth
option to meet their specific needs, tailoring the rule enforcement to match preferred coding guidelines.
Disallow the use of alert
, confirm
, and prompt
function showWarning() {
alert("This is a warning message!");
}
-
Improves user experience: Usage of methods like
alert
,confirm
, andprompt
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
, andprompt
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
withconsole.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.
Disallow Array
constructors
// Example of creating an empty array (not preferred)
const emptyArray = new Array();
// Example of creating an array with a single numerical argument, leading to an array of that length
const arrayWithLength = new Array(5);
// Example of creating an array with multiple arguments
const arrayWithElements = new Array('apple', 'banana');
-
This rule enforces the use of more readable and concise syntax for creating arrays, such as using array literals (
[]
) instead of theArray
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.
Disallow using an async function as a Promise executor
const getData = new Promise(async (resolve, reject) => {
try {
const data = await fetch("http://example.com/");
resolve(data);
} catch (error) {
reject(error);
}
});
-
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.
Disallow await
inside of loops
async function fetchUrls(urls) {
let results = [];
for (let i = 0; i < urls.length; i++) {
const response = await fetch(urls[i]); // Violates `no-await-in-loop`
const data = await response.json();
results.push(data);
}
return results;
}
-
The rule
no-await-in-loop
helps in identifying performance pitfalls in asynchronous code whereawait
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 usingPromise.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.
Disallow bitwise operators
// Here, a bitwise AND is used to check if a number is odd or even.
function isEven(num) {
return (num & 1) === 0;
}
// Using a bitwise OR to convert a float to an integer.
const floorValue = 5.76 | 0;
// Using a bitwise XOR to swap values without a temporary variable.
let a = 1, b = 2;
a = a ^ b;
b = a ^ b;
a = a ^ b;
-
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.
Disallow use of the Buffer()
constructor
// Using Buffer constructor directly
var buffer1 = Buffer(10);
// Using `new` with Buffer constructor
var buffer2 = new Buffer(10);
-
The rule targets the prevention of using the deprecated
Buffer()
constructor either directly or with thenew
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 asBuffer.from()
,Buffer.alloc()
, orBuffer.allocUnsafe()
contributes to more stable and secure code. -
It encourages using safer alternatives like
Buffer.from()
andBuffer.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.
Disallow the use of arguments.caller
or arguments.callee
function factorial(n) {
if (n <= 1) {
return 1;
} else {
// Usage of arguments.callee is discouraged
return n * arguments.callee(n - 1);
}
}
function whoCalled() {
if (arguments.caller) { // Usage of arguments.caller is discouraged
var callerString = arguments.caller.toString();
console.log("Called by: " + callerString);
} else {
console.log("The function was called from the top level");
}
}
- The rule helps enforce good coding practices by disallowing the use of
arguments.caller
andarguments.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. - By preventing the use of these properties, the rule aids in maintaining code security.
arguments.caller
andarguments.callee
can lead to potential security vulnerabilities by exposing stack trace details or allowing function calls in unintended ways. - This rule encourages more maintainable code. Using named functions or passing functions explicitly as arguments, instead of relying on
arguments.callee
, makes the code more readable, easier to debug, and adherent to modern JavaScript standards. - It aids in enhancing performance. The use of
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.
Disallow lexical declarations in case clauses
switch (key) {
case 'value1':
let x = 1;
console.log(x);
break;
case 'value2':
console.log('Case 2');
break;
default:
console.log('Default case');
}
- This ESLint rule prevents accidental global variable declarations by enforcing that variables are not declared with
let
orconst
directly within a case clause. Sincelet
andconst
have block-level scope, declaring them without a block in a case clause could lead to unexpected behavior or scope leakage. - It encourages a best practice of using blocks within case clauses to contain lexical declarations, thereby reducing potential bugs related to scope issues. By wrapping case clause contents in a block, variables declared with
let
orconst
are correctly scoped to the case, preventing them from being accessible in other cases. - This rule helps maintain consistency in how cases are structured within switch statements, which can improve code readability. By requiring declarations to be contained within blocks, it becomes easier for developers to identify the scope and extent of variables, making the code easier to follow.
- It aids in preventing errors that could arise from variable hoisting and unintended redeclarations. In JavaScript,
var
declarations are hoisted to the top of their function scope, butlet
andconst
are not. This rule ensures that when developers uselet
orconst
in case clauses, they are explicitly aware of the block scope, reducing the chance of redeclaration or hoisting issues.
Disallow catch
clause parameters from shadowing variables in the outer scope
let error = 'Some initial error';
try {
// Some risky operation that might throw
} catch (error) { // This error parameter shadows the outer `error` variable
console.log(error);
}
-
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.
Disallow reassigning class members
class Foo {
constructor() {
this.bar = 'bar';
}
}
Foo.prototype.bar = function() {
console.log('This should not happen.');
};
let fooInstance = new Foo();
fooInstance.bar(); // This attempts to call the reassigned function
- Ensures class integrity by preventing unintended modifications to class members, which can lead to hard-to-track bugs when class instances behave unpredictably due to externally modified prototype methods or properties.
- Promotes better class design and structure by encouraging the declaration of all member functions and properties within the class body, enhancing readability and maintainability of the code.
- Helps maintain a clear and predictable object-oriented programming model by enforcing the immutability of class members post declaration, preserving the designed behavior of class instances throughout the application lifecycle.
- Aids in spotting and correcting potentially malicious or erroneous code practices that involve altering class prototypes or instances in ways not originally intended by the class designer, thus improving the security and reliability of the application.
Disallow comparing against -0
if (value === -0) {
console.log("Value is negative zero!");
}
if (value > -0) {
console.log("Value is greater than negative zero!");
}
if (-0 <= value) {
console.log("-0 is less than or equal to value");
}
- This rule prevents the misuse of comparison operators with -0, which is crucial because in JavaScript, -0 and 0 are considered equal in numerical comparisons, but they are different values that can behave differently in certain contexts (e.g., when used as a divisor). Ensuring developers don’t mistakenly compare with -0 intending to distinguish it from 0 helps maintain the correctness of the code.
- It encourages the use of
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. - Comparisons against -0 using operators like
==
,===
,>
, 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. - The rule also implicitly encourages developers to reconsider the necessity and meaning of comparing against -0, potentially leading to clearer and more meaningful comparisons. It indirectly promotes better programming practices by making developers think about what they are actually trying to achieve with their comparisons, thus leading to more robust and understandable code.
Disallow assignment operators in conditional expressions
let x;
if (x = getValue()) {
console.log('The value is truthy!');
}
-
This rule helps prevent accidental assignments in conditional expressions, which are a common source of bugs. For example, using
=
instead of==
or===
in anif
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.
Disallow arrow functions where they could be confused with comparisons
const isGreater = a => a > 5 ? "Yes" : "No";
-
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
andonlyOneSimpleParam
give developers flexibility in enforcing this rule. Projects that favor minimal syntax can opt to disableallowParens
, 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.
Disallow the use of console
// Logs information to the console - not allowed per the `no-console` rule.
function fetchData() {
console.log('Fetching data...');
// Imagine an API call here
console.error('Error fetching data');
}
- This rule discourages the use of
console
logging in production code since logging can potentially expose sensitive information to the console, which is deemed insecure especially in a production environment. - By enforcing the removal of
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. - The rule provides options to allow certain console methods (if explicitly configured), which adds flexibility for development scenarios where developers might need to allow specific types of console logging (e.g.,
console.warn
orconsole.error
) temporarily, without completely disregarding the utility of console methods for debugging purposes. - It includes checks to prevent automatic removal of console statements if such action would cause syntax errors or alter the semantic structure of the code unintentionally. This cautious approach ensures that suggested code fixes do not introduce new errors or modify the behavior of the program.
Disallow reassigning const
variables
const number = 42;
number = 69; // This line violates the `no-const-assign` rule
console.log(number);
- Ensures the immutability of variables declared with
const
, directly upholding the language’s intended use ofconst
to declare constants which should not be reassigned after their initial definition. This helps maintain data integrity and predictability throughout the code. - Prevents runtime errors that occur when code mistakenly attempts to reassign a
const
variable. By catching these attempts early, it aids in reducing potential debugging time and improves code reliability. - Encourages the use of proper variable declarations that reflect their intended use within the codebase, guiding developers to deliberate on whether a variable’s value is intended to be immutable (
const
) or mutable (let
). - Enhances code readability and maintainability by making variable usage intentions clear. Other developers can immediately understand that variables declared with
const
are not meant to be changed, improving comprehension and reducing the likelihood of accidental reassignments.
Disallow expressions where the operation doesn’t affect the value
const isActive = true && getUserStatus();
- Prevents inefficient code by disallowing binary expressions that use constants in a way where the operation does not affect the outcome, improving the readability and maintainability of the code. For example,
const isActive = true && getUserStatus();
can be simplified toconst isActive = getUserStatus();
. - Enhances the code’s performance slightly by eliminating unnecessary logical operations. In the provided example, removing the constant
true &&
operation reduces the amount of work the JavaScript engine needs to do to evaluate the expression. - Helps to identify logical errors or misunderstandings in how logical operators work. A developer might erroneously assume that a constant expression could affect the outcome, leading to potential bugs or unintended behavior in the application.
- Promotes cleaner, more direct code expressions by encouraging developers to directly use variable or function expressions without embedding them in unnecessary logical structures. It drives the development towards best practices in expressing conditions or operations in a clear and concise manner.
Disallow constant expressions in conditions
// Using a constant condition in a while loop
while (true) {
console.log("This loop will run infinitely.");
}
- Preventing the use of constant expressions as conditions helps avoid infinite loops that can freeze or crash the application inadvertently, an issue demonstrated in the provided bad code example where
while (true)
creates an endless loop. - By disallowing constant conditions in conditional statements and loops, this rule promotes the implementation of more dynamic logic that can react to changes over time, encouraging developers to write conditions that can evaluate differently as the program’s state changes.
- Enforcing this rule helps identify sections of code that are potentially unreachable or represent logical errors, improving code readability and maintainability. For instance, an
if
statement with a constant condition might inadvertently hide code that is never executed or was intended to run under certain circumstances. - The rule’s configuration options, including the ability to check conditions within loops by default, provide flexibility to projects, allowing teams to adapt the rule to their specific needs while ensuring critical checks for constant conditions are enforced to prevent common pitfalls. This adaptability helps teams maintain high code quality standards without sacrificing their unique requirements.
Disallow returning value from constructor
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
if (width <= 0 || height <= 0) {
return null; // This is not allowed, constructors shouldn't return a value.
}
}
}
-
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.
Disallow continue
statements
// Using continue in a for loop
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i); // This will only log odd numbers
}
-
The
no-continue
rule encourages writing more straightforward loop logic by disallowingcontinue
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 bycontinue
. -
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 wherecontinue
might skip necessary incrementation or evaluation at the end of a loop, rewriting the loop to avoidcontinue
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.
Disallow control characters in regular expressions
// This example contains a control character within the regex pattern
const regex = /\x1f/;
const testString = "Sample text containing\x1f a control character.";
const match = testString.match(regex);
console.log(match); // This will log the matched control character, if any
- This rule helps to avoid unintentional matching or processing of control characters in strings, which could lead to unexpected behavior or security vulnerabilities in applications that process user-generated content or data from external sources.
- By disallowing control characters in regular expressions, it ensures that the regular expressions are safer and less likely to be exploited for injection attacks, as control characters are often used in regex-based exploits.
- It improves code readability and maintainability by ensuring that regular expressions within the codebase do not contain obscure control characters, making the intended pattern matching more apparent to developers.
- Enforcing this rule can aid in debugging, as unexpected issues arising from inadvertent control character matches can be challenging to diagnose, saving developers time and reducing the possibility of bugs related to character encoding or processing.
Disallow the use of debugger
function debugExample() {
let x = 5;
let y = 3;
debugger; // This is bad because it uses `debugger`.
return x + y;
}
- Preventing the use of
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. - The rule helps maintain code quality and consistency across the project by enforcing a policy that disallows the use of inline debugging tools, encouraging the use of more sophisticated debugging techniques and tools.
- It aids in promoting better performance practices by preventing the deployment of code that could potentially trigger breakpoints in production environments, leading to a smoother user experience.
- By flagging the use of
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.
Disallow deleting variables
var myVar = "Hello, world!";
delete myVar; // This operation is disallowed.
-
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
orundefined
is a valid way to “empty” its value, contrasting with thedelete
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 withvar
,let
, orconst
. This distinction is crucial for developers to understand the limitations and proper uses of thedelete
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.
Disallow equal signs explicitly at the beginning of regular expressions
var re = /=foo/;
- This rule prevents the misunderstanding between the division operator and the start of a regex, enhancing code readability. Regular expressions starting with an equal sign (
/=
) can be confused for a division operation followed by an equal sign, especially in complex expressions. - It enforces a coding style where regular expressions are clearly distinguished from other operators, making the intent of the code more immediately apparent. By requiring the equal sign to be enclosed in brackets (
/[=]/
), it highlights that the character is part of the regex pattern and not an operator. - This rule can help avoid runtime errors by ensuring regular expressions are correctly interpreted by the JavaScript engine. Misinterpretation of the intent could lead to code that compiles but fails to behave as expected when executed.
- It simplifies the code maintenance process by standardizing how equal signs are used in regular expressions across the codebase. When developers follow this guideline, it’s easier for others to understand the purpose and mechanism of regular expressions without needing to delve into context or debug unnecessary errors.
Disallow duplicate arguments in function
definitions
function sum(a, b, a) {
return a + b + a;
}
- Helps prevent errors caused by typo or oversight, ensuring that function parameters are uniquely named which can lead to unintended behavior when accessing these parameters within the function body.
- Improves code readability and maintainability by enforcing a clear contract for the function’s interface. When parameters are uniquely named, it’s easier for developers to understand the role of each parameter without confusion.
- Facilitates better debugging and error tracking by eliminating the possibility of logical errors that might stem from unintentional variable shadowing within a function scope, making it straightforward to diagnose issues related to parameters.
- Enhances code quality and consistency across the codebase by adhering to a common best practice of defining functions, thereby promoting a higher standard of coding practices and reducing the risk of bugs related to parameter handling.
Disallow duplicate class members
class Person {
constructor(name) {
this.name = name;
}
sayName() {
console.log(`My name is ${this.name}`);
}
// Duplicate class method
sayName() {
console.log(`Hello, my name is ${this.name}`);
}
}
- Prevents accidentally defining multiple class members (methods or properties) with the same name, which can lead to unexpected behavior in code execution, as the last defined member would override all previously defined ones with the same name.
- Enhances code readability and maintainability by ensuring each class member has a unique name, making it easier to understand the class structure and its functionalities without the confusion of duplicate names.
- Helps in avoiding subtle bugs that may arise from misunderstanding which class member (method or property) is being called or used at runtime, especially in large and complex classes where tracking all members can be challenging.
- Encourages best coding practices, such as properly planning class member names and functionalities upfront, thereby reducing the need for future code refactoring and minimizing potential errors during codebase evolution.
Disallow duplicate conditions in if-else-if chains
let a = 10;
if (a > 5) {
console.log("a is greater than 5");
} else if (a == 10) {
console.log("a is equal to 10");
} else if (a > 5) { // Duplicate condition
console.log("a is again greater than 5");
} else {
console.log("a is less than or equal to 5");
}
- The rule helps in catching logical errors that might occur due to duplicate conditions in if-else-if chains, potentially preventing unintended code execution paths that could lead to bugs or incorrect application behavior.
- Enhances code readability and maintainability by ensuring that each branch in an if-else-if chain tests a unique condition, making it easier for developers to understand the logic and flow of the decision-making process in the code.
- By disallowing duplicate conditions, this rule encourages developers to optimize their conditional logic, potentially leading to more efficient code by eliminating unnecessary checks that do not change the outcome of the decision-making process.
- It ensures consistent evaluation behavior across different parts of the codebase by enforcing a systematic approach to writing conditional statements, thereby reducing the risk of introducing discrepancies in how similar conditions are evaluated in different sections of the application.
Disallow duplicate keys in object literals
const user = {
name: "John Doe",
age: 30,
name: "Jane Doe" // Duplicate key 'name'
};
- The rule helps maintain code consistency by ensuring all keys in an object literal are unique, which directly affects readability and maintainability. By disallowing duplicate keys, developers avoid unintentional value overwrites that could lead to bugs that are difficult to detect.
- This rule prevents a common source of runtime errors in JavaScript. When duplicate keys exist, the last key-value pair is the one that’s actually used, which could unintentionally override previous values. By enforcing no duplicate keys, the rule ensures that each property in an object literal has a unique identifier, reducing the risk of bugs related to unexpected value overrides.
- The enforcement of this rule aids in the development of good coding practices among developers, especially those new to JavaScript or to programming in general. By catching these issues early in the development process, it educates developers about potential pitfalls in JavaScript object initialization, leading to a higher overall code quality.
- This rule enhances code analysis tools’ effectiveness by providing a clear, enforceable pattern that can be automatically checked. This reduces the need for manual code reviews to catch these specific types of errors, thereby streamlining the development process and allowing teams to focus on more complex problems that require human intervention.
Disallow duplicate case labels
switch (value) {
case 1:
console.log("One");
break;
case 2:
console.log("Two");
break;
case 1: // Duplicate case label
console.log("Another one");
break;
default:
console.log("Default");
}
- Ensures code uniqueness within switch statements by disallowing duplicate case labels, which is crucial for maintaining clear logic flow and preventing unexpected behavior during case evaluation.
- Prevents errors related to repeated case labels that could lead to unexpected or undefined behavior in code execution, improving the reliability and predictability of the switch statement.
- Enhances code readability and maintainability by ensuring each case is unique, making it easier for developers to trace logic paths without confusion caused by duplicate cases.
- Promotes best coding practices by enforcing the elimination of redundant code, which can optimize performance by preventing unnecessary evaluations and making the codebase cleaner and more efficient.
Disallow duplicate module imports
// Bad code - violating no-duplicate-imports
import { merge } from 'lodash';
import something from './someFile';
import { find } from 'lodash'; // Duplicate import from the same module
function doSomething() {
console.log(merge, find, something);
}
- Increases code maintainability by ensuring all imports from the same module are consolidated in a single line. This makes it easier for developers to see what dependencies a module has at a glance.
- Helps in reducing the risk of import or dependency conflicts that might arise when the same module is imported multiple times in different places, potentially with different members or aliases.
- Improves code readability by eliminating redundancy. When imports from the same source are combined, it reduces clutter in the codebase, making it more streamlined and easier to understand.
- Encourages better organization of code and import statements, which can lead to more efficient code by preventing the unintentional import of the same module multiple times, potentially impacting bundle size if not properly tree-shaken.
Disallow else
blocks after return
statements in if
statements
function test(num) {
if (num > 10) {
return true;
} else {
return false;
}
}
-
Improves Readability: Using the
no-else-return
rule makes the code easier to read by eliminating unnecessaryelse
blocks afterreturn
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 areturn
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 theelse
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.
Disallow empty character classes in regular expressions
// This regular expression aims to match only digits, but it incorrectly includes an empty character class
const regex = /^[\d][]{1,}$/;
-
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.
Disallow empty functions
// BAD CODE
function doSomething() {}
let doAnotherThing = function() {};
const doYetAnotherThing = () => {};
-
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.
Disallow empty destructuring patterns
// Trying to destructure an array with an empty pattern
const [] = someArray;
// Trying to destructure an object with an empty pattern
const {} = someObject;
-
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.
Disallow empty static blocks
class MyClass {
static {
// This is an empty static block
}
}
- This rule specifically targets empty static blocks within classes, ensuring that any static initialization block actually performs initialization or logic. It helps keep the code clean and purposeful by removing unnecessary structures that do not contribute to the code’s functionality.
- By disallowing empty static blocks, it reduces the confusion for other developers who might wonder if the block was left empty by mistake or if there was supposed to be initialization code that was accidentally removed. This can improve the readability and maintainability of the codebase.
- Enforcing this rule can potentially lead to performance benefits. Although modern JavaScript engines are highly optimized, removing empty static blocks eliminates the need for any evaluation of such blocks, however minimal it might be.
- It encourages developers to comment their code outside of static blocks if the intention of an empty block was to leave a comment for documentation purposes. This practice ensures comments are placed where they are more visible and logical, contributing to better code documentation practices.
Disallow empty block statements
function doNothing() {
}
try {
// Some operation that might throw
} catch (error) {
}
-
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.
Disallow null
comparisons without type-checking operators
if (value == null) {
console.log("value is null or undefined");
}
if (value != null) {
console.log("value is not null or undefined");
}
- Enforces explicit type checking by requiring strict equality operators (
===
,!==
) fornull
comparisons, helping developers avoid unintentional type coercion that could lead to bugs. - Increases code clarity and maintainability by making the intent of null checks more explicit and understandable, thus reducing the potential for confusion when reading the code.
- Helps in identifying potential bugs early during the development process by highlighting comparisons that could behave unexpectedly due to JavaScript’s loose equality (
==
,!=
) rules. - Promotes best practices in JavaScript programming by discouraging the use of loose equality operators with
null
, which can equatenull
withundefined
, possibly leading to unintended logical branches in the code.
Disallow the use of eval()
// Example of code that violates the 'no-eval' ESLint rule
function dynamicallyEvaluateCode(inputCode) {
eval(inputCode);
}
- This ESLint rule specifically targets the use of
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 disallowingeval()
, the rule helps to mitigate possible security vulnerabilities in the codebase. - The rule offers the ability to customize its enforcement through an option (
allowIndirect
), allowing for a degree of flexibility in application security practices. This is particularly useful in scenarios where indirect usage ofeval()
might be considered safe or necessary, thereby providing teams the option to tailor the rule to their project’s specific requirements. - It provides mechanisms to detect not just direct calls to
eval()
but also sophisticated cases whereeval
might be accessed indirectly through global objects orthis
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. - Through detailed analysis of the code’s scope and strict mode, the rule additionally accounts for subtle differences in how
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 unsafeeval
usage.
Disallow reassigning exceptions in catch
clauses
try {
// Some code that could throw an exception.
} catch (e) {
e = new Error('Something else happened.');
console.error(e);
}
- Prevents confusion and potential bugs by ensuring that the original error object caught by the
catch
clause is not overwritten. Overwriting exception variables can lead to loss of original error information, making debugging harder. - Enhances code readability and maintainability by encouraging the declaration of new variables for new errors rather than reusing the exception variable. This clarity helps other developers understand the flow of errors and exceptions more intuitively.
- Promotes best practices in error handling by discouraging a common anti-pattern. Modifying the caught exception variable often indicates an attempt to mask or change the original error, which can complicate error tracking and handling strategies.
- Helps in creating a consistent error-handling strategy across the codebase by enforcing a rule that error objects caught in
catch
blocks should remain immutable. This immutability makes the code more predictable and easier to reason about when diagnosing issues.
Disallow extending native types
Array.prototype.unique = function() {
return this.filter((value, index, self) => {
return self.indexOf(value) === index;
});
};
const arr = [1, 2, 2, 3];
console.log(arr.unique()); // Output: [1, 2, 3]
- It prevents conflicts and compatibility issues that may arise from changing or extending native type prototypes, thus ensuring more stable and predictable behavior of built-in types across different environments and JavaScript engine versions.
- By discouraging the modification of built-in prototypes, it promotes the use of more maintainable and clear patterns for achieving functionality, such as creating utility functions instead of extending native objects, which can improve code readability and reusability.
- This rule aids in detecting and avoiding potentially hazardous practices like extending native objects, which can lead to difficult-to-debug side effects in large codebases where the modification might not be immediately apparent to all team members.
- The rule enforces a best practice that helps in creating a barrier against inadvertently overriding or conflicting with existing or future built-in methods, ensuring that the code remains robust against changes in the JavaScript language specification.
Disallow unnecessary calls to .bind()
var x = function() {
console.log("This function does not use 'this'.");
}.bind(this);
-
The rule helps ensure that
.bind()
is used only when necessary, specifically when the function being bound actually usesthis
. This can prevent developers from mistakenly believing thatthis
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 usethis
. -
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.
Disallow unnecessary boolean casts
// Unnecessary boolean cast with "!!"
if (!!someVariable) {
console.log('This variable is truthy.');
}
// Unnecessary use of Boolean constructor in a condition
while (Boolean(anotherVariable)) {
console.log('Another variable is truthy.');
}
- The rule helps improve code readability by eliminating redundant boolean coercions, such as using
!!
orBoolean()
to convert a value to a boolean. These practices are unnecessary in contexts where JavaScript automatically coerces values to booleans, like in conditional statements. - It can potentially identify logical errors or misunderstandings of JavaScript’s type coercion, where a developer might use a boolean cast thinking it’s required to check a truthy or falsy value in places like
if
statements or while loops, hence promoting better understanding and cleaner use of the language’s features. - By suggesting the removal of unnecessary boolean casts, this rule can lead to slightly more performant code. Although the performance gains might be minor, removing unnecessary operations can contribute to faster execution in high-performance or large-scale applications.
- The rule also aids in standardizing code practices across a codebase, reducing the variety of ways conditions are checked or expressed. This helps new developers understand the code faster and reduces cognitive load when reading through conditions, leading to reduced bugs and easier maintenance.
Disallow unnecessary labels
outer: for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
break outer;
}
}
-
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.
Disallow unnecessary parentheses
let a = (b);
- This specific ESLint rule,
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. - The rule incorporates a nuanced understanding of JavaScript syntax and semantics, including precedence rules and the syntax-specific roles of parentheses. By doing so, it ensures that removal of extraneous parentheses doesn’t inadvertently alter the execution logic of the code. This precision aids in maintaining the original functionality of the code while simplifying its structure.
- It supports configurable exceptions for certain syntactic constructs, allowing teams to tailor it according to their coding standards or preferences. This flexibility makes the rule adaptable to a wide range of coding styles and practices, enabling teams to enforce consistency without compromising on their specific needs or principles.
- The rule provides auto-fixing capabilities, significantly reducing manual refactoring efforts required to adhere to this style guideline. This automation not only speeds up the code cleanup process but also helps in maintaining focus on more critical aspects of code review and development, thereby potentially improving developer productivity and code quality over time.
Disallow unnecessary semicolons
function greet() {
console.log("Hello, world!");
}; // Unnecessary semicolon here
for (let i = 0; i < 5; i++); { // Unnecessary semicolon here
console.log(i);
}
-
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.
Disallow fallthrough of case
statements
function getFruitColor(fruit) {
let color;
switch (fruit) {
case 'apple':
color = 'red';
// unintentional fallthrough without break or comment
case 'banana':
color = 'yellow';
break;
case 'kiwi':
color = 'green';
break;
default:
color = 'unknown';
}
return color;
}
-
This rule helps in maintaining the integrity of
switch
statements by ensuring that eachcase
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.
Disallow leading or trailing decimal points in numeric literals
let badExample1 = .5; // Leading decimal point without a leading zero.
let badExample2 = 123.; // Trailing decimal point without a trailing digit.
- This rule helps in increasing code readability and clarity by ensuring that numeric literals have leading and trailing digits when decimals are involved, making them easier to spot and understand at a glance. For example,
.5
is transformed into0.5
, and123.
is transformed into123.0
. - By enforcing consistency in the syntax of numeric literals, it prevents potential confusion or errors in interpretation, especially for those new to JavaScript or coming from languages with different conventions around decimal points.
- The rule offers automatic fixes that can standardize existing codebases without requiring manual intervention, thus saving time and reducing the likelihood of human error during code refactoring or review processes.
- It aligns with common style guides and best practices in JavaScript development, promoting a higher standard of code quality and maintaining a professional level of coding across collaborative projects by eliminating unconventional numeric expressions.
Disallow reassigning function
declarations
function greet() {
console.log('Hello, world!');
}
// Trying to reassign the function
greet = function() {
console.log('Goodbye, world!');
}
-
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.
Disallow assignments to native objects or read-only global variables
NaN = "Hello, World!";
console.log(NaN);
- This rule helps in preventing accidental global namespace pollution, which could lead to difficult-to-debug errors by ensuring assignments don’t inadvertently modify global objects or read-only variables.
- By disallowing assignments to native or read-only global variables, this rule aids in maintaining the integrity and expected behavior of these built-in objects, ensuring that code relies on predictable and standard behaviors.
- The rule facilitates the creation of more modular and encapsulated code. When developers are prevented from modifying globals, they are encouraged to use local variables or explicitly defined global namespaces, which can improve code maintainability and reusability.
- It has a mechanism for exceptions, allowing project-specific global variables that may need to be writable to be excluded from this restriction, providing flexibility in application configuration and reducing the chances of false positives in linting reports. This ensures that while the rule enforces good practices, it does not become an obstacle by being too rigid.
Disallow shorthand type conversions
const isActive = !!someValue;
- Ensures clarity in type conversion by requiring explicit conversion methods instead of using shorthand coercions. For example, converting a value to boolean using
Boolean(someValue)
instead of!!someValue
makes the developer’s intention clear and improves code readability. - Prevents potential bugs by making type conversions explicit. Implicit conversions like using
+
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. - Improves code maintainability by enforcing a consistent style for type conversions across the codebase. When all developers on a team use the same explicit methods for type conversion, it becomes easier to understand and review code.
- Facilitates easier debugging and code analysis by reducing the cognitive load required to understand type conversions. For instance, when a variable is explicitly converted using
Number(value)
orString(value)
, it’s immediately clear what the developer intended, as opposed to trying to infer intent from the context around shorthand coercions.
Disallow declarations in the global scope
var myGlobalVar = "This is bad practice.";
function myGlobalFunction() {
console.log("This function is globally accessible!");
}
- Prevents pollution of the global namespace by disallowing variable and function declarations in the global scope, which helps in maintaining a modular codebase where each module or component is responsible for its scope. This specificity ensures that variables or functions that are meant to be used locally within modules don’t unintentionally become global.
- Reduces the risk of naming collisions in the global scope, which can lead to bugs that are hard to track down. By enforcing that variables and functions are declared within a local scope, this rule makes sure that developers don’t accidentally overwrite global variables or functions that might be critical to other parts of the application or third-party libraries.
- Enhances code clarity and maintainability by making the scope and lifetime of variables and functions explicit. When variables and functions are declared locally, it’s easier for developers to understand where they can be accessed from and how they are used, without worrying about unintended side effects in other parts of the application.
- Encourages the use of immediately-invoked function expressions (IIFE) or module patterns which provide a clear mechanism for isolating code and explicitly controlling the exposure of variables and functions to the rest of the application. This rule, by disallowing implicit globals, nudges developers towards adopting patterns that improve the structure and security of the code.
Disallow the use of eval()
-like methods
// Example of code that violates the `no-implied-eval` rule
setTimeout("console.log('This is unsafe!');", 1000);
- This ESLint rule helps to mitigate security risks associated with the dynamic execution of code by prohibiting the use of
eval()
-like methods which can be exploited for malicious purposes such as executing arbitrary code. - By disallowing
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. - The rule encompasses not only direct calls to
eval()
but also other functions that can implicitly evaluate string expressions as code, such assetTimeout()
,setInterval()
, andexecScript()
. This comprehensive approach ensures a wider range of potentially harmful code patterns are caught and flagged. - Enforcing this rule helps in maintaining code clarity and predictability. Relying on string evaluations for executing code can obscure the functionality and flow of a program, making it harder for developers to understand and debug. In contrast, using explicit function calls or definitions makes the code more readable and maintainable.
Disallow assigning to imported bindings
// Assume existence of an external module 'myModule' with property 'value'
import { value } from './myModule';
function updateValue() {
// Illegal assignment to imported binding
value = 'newValue';
}
-
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.
Disallow inline comments after code
const x = 5; // This is an inline comment
console.log(x); // Print the value of x
-
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.
Disallow variable or function
declarations in nested blocks
function exampleFunction() {
if (true) {
function nestedFunction() {
console.log("This is not allowed.");
}
var nestedVar = "This is also not allowed.";
}
}
- This rule helps maintain a clear and predictable structure in the code by enforcing the declaration of variables and functions at the root level, rather than allowing them to be hidden within nested blocks. This makes the code easier to read and understand.
- By disallowing the declarations within nested blocks, it prevents potential hoisting issues that could lead to bugs. For example, function and var declarations are hoisted to the top of their enclosing function scope, which might not be the intended behavior if they were declared inside a conditional block.
- This rule directly contributes to reducing the complexity of functions by encouraging smaller, more focused functions, rather than large functions with many nested blocks of scope. It encourages developers to think about the scope and lifetime of their variables and functions, leading to better designed code.
- Applying this rule can also improve performance in some cases because it avoids creating new functions or variables every time a block of code is executed. This is especially relevant for functions declared within loops or frequently executed blocks.
Disallow invalid regular expression strings in RegExp
constructors
// Example of bad code
let re = new RegExp('\\');
console.log(re.test('some text'));
- Prevents runtime errors due to invalid regular expression patterns by statically analyzing RegExp constructor calls. This means issues can be caught at development time instead of causing potentially unhandled exceptions in production environments.
- Enhances code reliability by enforcing the validation of regular expression flags. Considering flags might alter the behavior of the regular expressions significantly, ensuring their correctness is essential to avoid unexpected behaviors.
- Improves code comprehension and maintenance by discouraging the use of confusing or unsupported syntax within regular expressions, particularly when making use of advanced features like unicode flags. This helps maintain consistency and predictability in how regular expressions are constructed and interpreted across different parts of a codebase.
- Assists in adhering to best practices and standards regarding regular expressions by prohibiting the combining of incompatible flags (
u
andv
), thus aligning with ECMAScript specifications and ensuring broader compatibility and predictability of regex behavior across different JavaScript engines.
Disallow use of this
in contexts where the value of this
is undefined
class MyClass {
constructor() {
this.myProperty = 5;
document.getElementById('myElement').addEventListener('click', () => {
console.log(this.myProperty); // `this` might not refer to the instance of MyClass
});
}
}
- This ESLint rule specifically helps to identify and prevent the usage of the
this
keyword in contexts where it might beundefined
, reducing the chances of runtime errors due to incorrect assumptions about the binding ofthis
. - It provides a mechanism to enforce best practices related to the use of
this
in various scopes, particularly in modular code where the global context does not automatically bind tothis
, thereby keeping the code more consistent and predictable. - By allowing configuration options like
capIsConstructor
, the rule offers flexibility in determining the validity ofthis
within constructor functions versus regular functions or methods, helping to align the rule’s behavior with the project’s coding standards or architectural decisions. - The rule’s design to defer the computation of whether
this
is valid until it is first encountered within a function optimizes performance by avoiding unnecessary computations for functions that do not usethis
, making the linting process more efficient without sacrificing thoroughness.
Disallow irregular whitespace
function greet(name) { // Assume an irregular whitespace exists after the opening brace
console.log("Hello, " + name); // Assume irregular whitespaces exist before `console.log`
}
-
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.
Disallow the use of the __iterator__
property
const myArray = [1, 2, 3];
const iterator = myArray.__iterator__;
while (true) {
const next = iterator.call(myArray);
if (next.done) break;
console.log(next.value);
}
-
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 usingSymbol.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 orSymbol.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.
Disallow labels that share a name with a variable
// Sample bad code
let loop = true;
myLoop: while(loop) {
console.log('Inside loop');
break myLoop;
}
- This rule helps in preventing confusion and enhancing code readability by disallowing the use of the same name for labels and variables within the same scope. This specificity aids in ensuring that developers don’t inadvertently refer to a variable when they intend to reference a label, or vice versa.
- By enforcing a separation between variable names and label names, this rule assists in avoiding errors that could arise from name shadowing, where a label might unintentionally take precedence over a variable with the same name, or it might not be clear which entity is being referred to.
- The rule contributes to cleaner code maintenance and refactoring practices. If a developer needs to change the name of either a label or a variable, having distinct names reduces the risk of modifying one but forgetting to update the other, thereby preserving the code’s intended functionality.
- The rule’s implementation includes a mechanism to recursively check the scope for identifier names, thereby ensuring that the validation is thorough and encompasses various levels of scope. This thoroughness is crucial in complex codebases where variables and labels might be defined in different scopes but could still lead to confusion if named identically.
Disallow labeled statements
loop1:
for (let i = 0; i < 10; i++) {
if (i === 3) {
break loop1;
}
console.log(i);
}
- The rule helps enforce a more readable and maintainable code structure by discouraging the use of labeled statements, which are often unnecessary and can make code less clear, especially for developers unfamiliar with the concept or the specific codebase.
- By allowing configuration options (
allowLoop
andallowSwitch
), 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. - The rule aids in preventing the misuse of labels that can lead to complex and error-prone code by enforcing structured programming practices, making it easier to understand the flow of the program without jumping through labeled sections.
- It promotes the use of simpler control flow mechanisms (like break and continue without labels) that are sufficient in most cases, encouraging developers to re-think their logic and refactor code in a way that avoids deep nesting or the need for jumping across code blocks, ultimately leading to cleaner and more straightforward code.
Disallow unnecessary nested blocks
function testFunction() {
// An unnecessary nested block
{
let x = 2;
console.log(x);
}
}
- This ESLint rule identifies and flags unnecessary nested blocks that do not contribute to the functionality of the code, helping to ensure that the code is as streamlined and readable as possible, thereby improving maintainability.
- By disallowing redundant blocks, it indirectly encourages developers to declare variables and functions in the appropriate scope, which can lead to better memory management and potentially reduce the scope lookup times during execution.
- The rule has the potential to uncover and mitigate subtle bugs related to block scoping, particularly with
let
andconst
declarations within unnecessary blocks, which might behave differently than the developer expects if misunderstood. - Implementing this rule can lead to a more consistent coding style across a project, as it discourages the use of stylistic choices that do not have any practical benefit, making the codebase easier for new developers to understand and contribute to.
Disallow if
statements as the only statement in else
blocks
if (condition) {
// Some code
} else {
if (anotherCondition) {
// Some other code
}
}
- Enhances code readability and conciseness by transforming nested
if
statements inelse
blocks intoelse if
constructs, making the code easier to understand at a glance. - Helps prevent deep nesting that can lead to harder to maintain and understand code structures, by encouraging a flatter conditional logic structure.
- The rule includes a fixer that automatically corrects the identified pattern, saving developer time and reducing the likelihood of manual error during refactoring.
- By disallowing lone
if
statements inelse
blocks, this rule promotes a coding style that can improve the overall quality of codebases by enforcing consistency in how conditional logic is written.
Disallow function declarations that contain unsafe references inside loop statements
for (var i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i); // Reference to the loop variable `i`
}, 100 * i);
}
-
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.
Disallow literal numbers that lose precision
// A very large number that cannot be precisely represented in JavaScript
const impreciseNumber = 123456789012345678901234567890;
- Ensures numeric literals in the codebase are accurately represented in memory, preventing inadvertent precision loss which can lead to unexpected behavior or bugs, especially with very large or precise numbers that JavaScript’s number type can’t handle accurately.
- Encourages representing numbers that can’t be precisely stored as number types in a safer way, such as strings, which can then be converted to BigInts or handled with libraries designed for precise arithmetic, improving the reliability of operations involving such numbers.
- Enhances code readability and maintainability by requiring developers to explicitly acknowledge and handle cases where numbers might lose precision, thus making it easier to understand the intent behind numeric representations and potentially identify logic errors.
- Specifically improves compatibility and future-proofing of JavaScript applications that deal with large numbers, scientific calculations, financial transactions, or any domain where numeric accuracy is paramount, ensuring that the application behaves correctly across different environments and JavaScript engines.
Disallow magic numbers
function calculateDiscount(price) {
return price - (price * 0.1); // 0.1 is a magic number
}
- Encourages the use of named constants instead of “magic numbers” in the code, making it clearer what a number represents, as demonstrated by the transition from using
0.1
directly in a calculation to defining it asDISCOUNT_RATE
. This improves code readability and maintainability by making the purpose of numbers clear. - Enhances the consistency of handling special values across the codebase by providing configurations such as
ignore
,enforceConst
, orignoreArrayIndexes
, allowing teams to tailor the rule to their project’s needs and ensuring that exemptions like array indexes or default values are handled uniformly. - Facilitates the identification and refactoring of potentially obscure or hardcoded values that could lead to errors or difficulties in understanding the code’s behavior. For example, replacing a hardcoded value with a named constant can prevent errors that might arise from changing the value in one place but not another.
- Supports customization to fit a wide range of coding practices and scenarios through options like detecting magic numbers within objects, enforcing constants, or ignoring specific values. This allows the rule to be applicable in diverse codebases without forcing a one-size-fits-all approach, catering to different use cases like setting default values or class field initial values.
Disallow characters which are made with multiple code points in character class syntax
// Suppose the character in question is a surrogate pair or a combined character
// Example: The character '' (U+1D306 TETRAGRAM FOR CENTRE) which is a surrogate pair in JavaScript
const regex = /[\u{1D306}]/; // Intended to match '', but is misleading in a character class without the 'u' flag
console.log("".match(regex)); // Unexpectedly null because the regex is not correctly formed to handle a surrogate pair
-
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 theu
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.
Disallow mixed binary operators
// This code example mixes different operators without properly grouping them with parentheses.
// This can lead to confusion about the order of operations.
const result = 5 + 10 * 3 - 2;
- Prevents confusion regarding the precedence and order of operations when multiple types of binary or logical operators are used together, as in the ‘bad’ example where
5 + 10 * 3 - 2
could confuse readers about the sequence of operations. - Enhances code readability and maintainability by enforcing a clearer, more explicit expression of intent through the grouping of operations with parentheses, as demonstrated in the ‘fix’ example
(5 + (10 * 3)) - 2
. - Helps avoid subtle bugs that might arise from misunderstandings of operator precedence, which is crucial in complex expressions where the outcome might not be what the programmer expects without explicit grouping.
- It provides a customizable configuration that can be tailored to the specific needs or guidelines of a project, for instance by allowing groups of operators to be mixed without warning if they have the same precedence, thus offering flexibility to adapt the strictness of the rule.
Disallow require
calls to be mixed with regular variable declarations
const fs = require('fs'),
path = require('path'),
myFunction = () => {
console.log("Hello, world!");
};
-
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
andallowCall
, the rule is flexible and can be adjusted to fit various coding conventions or project requirements. Thegrouping
option ensures thatrequire
calls are either all bunched together or separately declares, making it easier to identify dependencies at a glance. TheallowCall
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.
Disallow mixed spaces and tabs for indentation
function calculateSum(a, b) {
var total = a + b; // Line indented with spaces
return total; // Line indented with a tab
}
- Ensures consistency in indentation across your codebase, which can greatly improve readability and maintainability by making the code structure apparent.
- Helps avoid errors due to inconsistent indentation, such as difficulty in understanding the nesting level of code blocks, which can lead to bugs or misinterpretation of the code structure by developers.
- Supports “smart-tabs” option, allowing for flexible indentation policies where tabs are used for indentation and spaces for alignment, accommodating different coding styles while still enforcing consistency.
- Excludes lines within comments from the rule to prevent unnecessary warnings about mixed indentation solely within comment blocks, focusing the rule’s enforcement on the actual code and not documentation or comments within the code.
Disallow use of chained assignment expressions
let a = b = c = 5;
- This rule specifically prevents the use of chained assignment expressions, which are identified as a potential source of confusion or errors in code reading and maintenance. For example,
let a = b = c = 5;
can be misleading about the intention behind the assignment operation and the scope of variables being affected. - By disallowing chained assignments, it enforces clarity in initializing variables. The corrected approach of initializing each variable separately (
let c = 5; let b = c; let a = b;
) makes the code more readable and straightforward, thereby reducing the risk of unintentional errors. - The rule provides flexibility through its options, allowing users to disregard this rule for non-declaration assignments if they choose. This adaptability ensures that developers can enforce code clarity while still accommodating specific use cases where chained assignments might be considered acceptable.
- It directly targets a common programming shortcut that, while potentially reducing the number of lines of code, generally detracts from code comprehensibility and maintainability. This rule thereby promotes best practices in coding standards by emphasizing code quality over minimalism.
Disallow multiple spaces
const x = 5; // Unnecessary multiple spaces around the assignment and variable
let y = x + 2; // Unnecessary multiple spaces around the plus operator
function calculate( a, b ) { // Unnecessary multiple spaces inside the function parameters
let result = a + b; // Unnecessary multiple spaces around the assignment
return result;
}
- The rule helps in maintaining code consistency by ensuring that there are not multiple spaces in places where a single space is required according to common style guides. This consistency makes the code easier to read and maintain, especially in team environments where different developers might have varying spacing habits.
- By disallowing multiple spaces except for in cases where exceptions are explicitly defined, the rule allows for customizability to fit the specific needs or preferences of a project or team. For example, aligning assignments or comments for readability can be allowed by configuring exceptions.
- The rule includes an automated fix option, which can significantly reduce the time developers spend on formatting issues. This automatic correction helps maintain focus on logic and functionality rather than formatting, improving development efficiency.
- It provides clear feedback on why a particular spacing is considered an issue by including formatted comment values in the report. This aids developers in understanding the reason behind the reported issue, fostering a learning environment where developers can improve their coding practices based on feedback from linting tools.
Disallow multiline strings
// Bad code example for 'no-multi-str'
const errorMessage = 'This error message is too long and \
is split into two lines.';
-
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.
Disallow multiple empty lines
const a = 5;
// Excessive empty lines below, violating the no-multiple-empty-lines ESLint rule
const b = 10;
function doSomething() {
console.log("Doing something...");
}
console.log(a + b);
- This rule helps maintain a consistent code structure by limiting the number of consecutive empty lines, thereby preventing large, visually unappealing gaps in the code. This ensures the codebase is easier to read and navigate, especially in larger files where excessive whitespace could lead to more scrolling and less efficient code review or understanding of the code structure.
- The rule allows configuration of maximum consecutive empty lines at the beginning and end of files (maxBOF and maxEOF), as well as within the file (max), offering flexibility to adapt to different coding styles or team preferences. This means the rule can be tailored to the specific needs of a project without forcing a one-size-fits-all approach, balancing consistency with configurability.
- By automatically fixing violations of this rule, it can reduce the need for manual clean-up of whitespace issues, saving developer time and ensuring that code style conventions regarding whitespace are consistently applied without needing manual intervention. This automatic correction feature helps maintain code quality with minimal effort.
- The rule has an intelligent design that respects the semantic significance of empty lines within template literals, avoiding unintentional alteration of code that relies on whitespace for its functionality. Therefore, it ensures that while maintaining code style and readability, the functionality of the code is not compromised, demonstrating a careful consideration of JavaScript’s nuances in its implementation.
Disallow assignments to native objects or read-only global variables
undefined = true;
- Prevents the accidental overwriting or assignment to native objects and read-only global variables, which can lead to unpredictable behavior or errors in the code, ensuring that the foundational elements of the JavaScript environment remain intact and reliable.
- By disallowing modifications to native objects or read-only globals, this rule helps maintain the integrity and stability of the execution context, making the code safer and less prone to runtime errors that could arise from such modifications.
- This rule enhances code maintainability by ensuring that developers do not inadvertently assign values to read-only global variables, which could lead to confusing bugs that are difficult to trace and resolve.
- It promotes best practices in JavaScript programming by enforcing a constraint that prevents potentially harmful actions like reassigning values to objects such as
window
orundefined
, which could lead to severe implications for the application’s functionality.
Disallow negated conditions
function showAuthenticationButton(user) {
if (!user.isLoggedIn) {
console.log('Show login form');
} else {
console.log('Show logout button');
}
}
- The rule helps in making the code more readable by encouraging the use of positive conditionals over negative ones. This can make it easier for developers, especially those who might not be as fluent in the language of the codebase, to understand the logic at a glance without having to mentally invert conditions.
- It aims to reduce the cognitive load on developers. Negated conditions require an extra step of logic (understanding what the condition is not) before understanding what the code will execute, whereas non-negated conditions directly state what is expected for the code to proceed.
- By discouraging the use of negated conditions, the rule also promotes consistency in how conditions are checked throughout the codebase. This uniformity can make it simpler to maintain and refactor code, as developers can expect conditions to be structured in a similar fashion across various parts of a project.
- The rule may indirectly lead to identifying overly complex logic or conditions within the code. If a condition is difficult to express in a non-negated form, it might indicate that the overall logic could benefit from simplification or being broken down into smaller, more manageable parts. This can improve both the readability and maintainability of the code.
Disallow negating the left operand in in
expressions
// Checking if a property does not exist in an object in a confusing manner
if (!'property' in object) {
// Some logic here
}
-
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.
Disallow nested ternary expressions
const getStatus = (status) => {
return status === 'active' ? 'Active' : status === 'pending' ? 'Pending' : 'Inactive';
};
-
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.
Disallow new
operators with the Function
object
// Example of code that violates the no-new-func ESLint rule
let sum = new Function('a', 'b', 'return a + b');
console.log(sum(2, 6)); // Outputs: 8
- This ESLint rule specifically targets and disallows the use of the
Function
constructor withnew
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. - It encourages developers to adopt safer and more predictable alternatives for defining functions, such as function expressions or function declarations, which do not involve dynamic code evaluation and are therefore less prone to security vulnerabilities.
- The rule helps in maintaining consistency in codebases by enforcing a uniform way of declaring functions, avoiding the mix of function constructors with
new
and other function declaration styles, leading to more maintainable and readable code. - By automatically identifying and reporting instances where the
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.
Disallow new
operators with global non-constructor functions
// Bad because String is a non-constructor function
const myString = new String("Hello, world!");
console.log(myString); // This doesn't behave as a typical string
- It prevents the misuse of global non-constructor functions with the
new
operator, which can lead to unexpected behaviors and bugs in the code. For example, usingnew String("Hello, world!")
creates an object instead of a primitive string. - The rule enforces a coding standard that promotes the use of non-constructor global functions in their intended form, thereby improving code clarity and maintainability. This makes it easier for developers to understand the code, as it aligns with the expected use of JavaScript global functions.
- By disallowing the
new
operator with non-constructor functions, this rule helps optimize the runtime performance of JavaScript applications. Objects created through the misapplication ofnew
with functions likeString
orNumber
can have a larger memory footprint and worse performance compared to their primitive counterparts. - It aids in the early identification of likely mistakes in the use of global functions, reducing the time spent on debugging issues related to types. For instance, identifying that
new String()
does not return a primitive string can be non-intuitive, especially for developers less familiar with JavaScript’s nuances.
Disallow Object
constructors
// This code violates the 'no-new-object' rule
const myObject = new Object();
myObject.name = "John Doe";
myObject.age = 30;
- This rule insists on using object literal notation (
{}
) over thenew 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. - It prevents the accidental creation of a global
Object
if the code is executed in a context whereObject
might not refer to the native JavaScript Object constructor due to shadowing or redefinition, thus safeguarding against potential bugs. - Applying this rule can improve performance slightly as using
{}
is faster than invoking a constructor function likenew Object()
, due to less overhead in the object creation process. - It encourages the use of more descriptive and semantically clear ways to create objects, paving the way for code that is easier to understand and maintain. Using object literals from the start allows for immediate property definition, which can be more efficient and clearer in intent.
Disallow new
operators with calls to require
const fs = new require('fs');
-
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 ofrequire
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
withrequire
could potentially lead to incorrect initializations or unexpected behaviors in modules, as most modules exported withmodule.exports
are not designed to be instantiated withnew
. 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 unnecessarynew
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
withoutnew
), 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.
Disallow new
operators with the Symbol
object
const mySymbol = new Symbol("description"); // This is incorrect and will cause an error
-
Ensures compliance with ECMAScript specification: The JavaScript specification defines the
Symbol
as a primitive value that cannot be constructed usingnew
. 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 becauseSymbol
is not a constructor. By disallowing thenew
operator withSymbol
, 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 ofSymbol
, 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 thenew
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.
Disallow new
operators with the String
, Number
, and Boolean
objects
let myString = new String("Hello");
let myNumber = new Number(123);
let myBoolean = new Boolean(false);
- The rule helps enforce consistency by discouraging the use of object wrappers for primitives, which can lead to type confusion since objects and primitive values behave differently in JavaScript. For instance, objects are truthy regardless of their wrapped value, which can cause unexpected bugs in conditional statements.
- It promotes the use of primitive values directly (
"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. - By flagging uses of the
new
operator withString
,Number
, andBoolean
, 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. - Preventing the use of these wrapper objects with the
new
operator can help avoid unexpected behavior in equality checks. Sincenew 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.
Disallow new
operators outside of assignments or comparisons
// Bad: Using `new` without storing the resulting object or using it in a comparison
function createLogger() {
new Logger('info');
}
createLogger();
- It prevents the creation of objects through the
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. - Enhances code readability and maintainability by making it clear which objects are being created and for what purpose. When new objects are stored in variables or used in comparisons, it makes the code easier to understand for other developers or for future reference.
- Helps in identifying potential errors in the code where objects are instantiated using
new
but are never utilized, which can be a sign of incomplete implementation or a misunderstanding of how the objects should be used. - Encourages better coding practices by making developers more deliberate about their use of the
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.
Disallow \8
and \9
escape sequences in string literals
// Bad example: Using \8 and \9 escape sequences
const myString = "Example: \8 and \9";
- The rule “no-nonoctal-decimal-escape” specifically targets the disallowance of
\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. - It provides automatic fix suggestions, which not only highlight the issue to developers but also offer immediate rectification options, thereby saving time and reducing the potential for manual error during the correction process. For instance, transforming
\8
and\9
into their respective Unicode escapes or simply suggesting the removal of the backslash to avoid creating unintended escape sequences. - This rule enhances code readability and maintainability by ensuring that all string literals follow a consistent and understandable pattern, avoiding the ambiguous and potentially misleading use of
\8
and\9
escapes which do not have a clear or defined behavior in JavaScript. - By offering suggestions for different contexts, such as when a
\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.
Disallow calling global object properties as functions
// Incorrect usage of global objects
const number = Math(5.76); // attempting to use `Math` as a function
const myObject = JSON('{"name": "John"}'); // attempting to use `JSON` as a function
-
This rule directly targets a common misunderstanding among JavaScript developers where global objects like
Math
andJSON
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.
Disallow calls to the Object
constructor without an argument
// A function that unnecessarily uses the Object constructor without arguments.
function createEmptyObject() {
return new Object();
}
- Promotes the use of more concise and idiomatic JavaScript code by encouraging the use of
{}
for creating empty objects instead ofnew Object()
, which aligns with modern JavaScript best practices and can make the code easier to read and understand. - Helps in increasing code performance slightly, as using object literals (
{}
) can be more optimized by JavaScript engines compared to using theObject
constructor without arguments. This can contribute to minor improvements in the execution time of scripts, especially in environments where performance is critical. - Aids in maintaining consistency across the codebase by discouraging the use of different styles for creating empty objects, which can help new team members to understand the code better and reduce the cognitive load when switching between different parts of the project.
- Prevents potential confusion or errors that might arise from using the
Object
constructor without arguments. For instance, in cases where the globalObject
could have been shadowed or overwritten, leading to unexpected behavior. Enforcing the use of object literals removes the reliance on the globalObject
constructor, thereby reducing the risk of such issues.
Disallow octal escape sequences in string literals
// Example of bad code that includes an octal escape sequence
const message = "An example of an old escape sequence: \251";
console.log(message);
- It ensures that string literals do not contain octal escape sequences, which are deprecated in ECMAScript standards, promoting the use of more modern and universally accepted escape sequences like Unicode (\uXXXX) instead. This helps in enhancing code readability and maintainability.
- By disallowing octal escape sequences, the rule helps avoid confusion between octal and decimal numbers in strings, which can lead to misinterpretation of the intended character representation, especially for developers who may not be familiar with octal notation.
- The rule aids in codebase uniformity by enforcing a consistent method of representing special characters in strings. This uniformity is especially beneficial in large projects or teams where consistency in coding practices can significantly reduce bugs and improve code quality.
- It plays a crucial role in preparing the code for future ECMAScript versions and environments that might not support octal escape sequences, thereby ensuring that the code is more future-proof and less likely to encounter compatibility issues.
Disallow octal literals
const octalValue = 071;
console.log(octalValue); // In an octal-aware environment, this logs 57, not 71, which can be confusing
- This ESLint rule specifically targets the use of octal literals in JavaScript code, which can lead to confusion and bugs because octal notation is not widely used or understood by all developers. When a number is prefixed with a zero followed by another digit (e.g.,
071
), it might be interpreted as an octal number rather than a decimal, affecting the program’s logic unexpectedly. - By disallowing octal literals, this rule helps ensure that all numeric literals in the codebase are interpreted as intended by the developer, particularly in contexts where octal and decimal numbers might be easily confused. This consistency can prevent subtle, hard-to-find bugs in calculations or data processing, contributing to the overall reliability of the application.
- The rule enforces a more uniform coding style by requiring developers to use decimal literals (or explicitly use hexadecimal, binary, etc., when necessary), which are more universally understood. This uniformity makes the code easier for new team members to understand and reduces the cognitive load when reading and reviewing code, as there’s one less nuance to keep in mind.
- Since octal literals are deprecated in ECMAScript strict mode and can lead to errors if used unintentionally, enforcing the use of decimal (or another explicit notation) helps ensure that the code is future-proof and compatible with modern JavaScript standards. This adherence to standards helps in avoiding potential issues when moving code to different environments that enforce strict mode or when upgrading JavaScript engines.
Disallow reassigning function
parameters
function addToScore(player, points) {
player.score += points; // Reassigning a property of the function parameter
// rest of the function
}
function incrementValue(value) {
value += 1; // Directly reassigning the function parameter
return value;
}
-
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.
Disallow string concatenation with __dirname
and __filename
// Violates `no-path-concat` rule
const filePath = __dirname + "/config.json";
- This rule helps in promoting the use of path-specific methods like
path.join()
orpath.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. - Enforcing this rule mitigates the risk of creating incorrect file paths that can lead to runtime errors. For example, on Windows, paths use a backslash (
\
) 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. - It inherently encourages developers to utilize the Node.js
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. - By discouraging string concatenation with
__dirname
and__filename
, this rule also promotes code readability and maintainability. Usingpath.join
orpath.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.
Disallow the unary operators ++
and --
let count = 0;
for (let i = 0; i < 10; i++) {
count++;
}
- It enforces a consistent increment/decrement style across your codebase, avoiding the mixed use of
++
,--
, and+= 1
or-=
operators, which can lead to more readable and maintainable code. - The rule specifically allows for exceptions in for-loop afterthoughts when configured, making it flexible enough to accommodate common coding patterns where
++
and--
are traditionally accepted, while still enforcing the rule elsewhere. - By disallowing the unary operators
++
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. - It can make code review and understanding code behavior easier for teams, especially those new to JavaScript or coming from other programming languages where increment and decrement shortcuts might behave differently or are not used as frequently.
Disallow the use of process.env
// Accessing an environment variable directly with process.env
const dbPassword = process.env.DB_PASSWORD;
console.log(`Database password is: ${dbPassword}`);
-
The rule
no-process-env
specifically targets the direct use ofprocess.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.
Disallow the use of process.exit()
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello World!');
if (someCondition) {
console.log('Exiting due to some condition');
process.exit(1); // Disallowed by no-process-exit
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
- Encourages the use of proper error handling and response mechanisms in server environments instead of abruptly terminating the application with
process.exit()
, which could lead to a poor user experience by not fulfilling the request properly or providing helpful feedback. - Prevents potential disruption of service in server applications running in a shared process environment (like Node.js apps), where a call to
process.exit()
would ungracefully shut down the entire process, affecting all ongoing and future requests. - Promotes application resilience by enforcing developers to think about graceful degradation and error recovery strategies, thereby improving the overall stability and reliability of the application.
- Enhances the maintainability of the codebase by discouraging the use of global process controls for local error handling, leading to clearer, more modular, and easier-to-understand code that handles errors at the appropriate level of scope.
Disallow returning values from Promise executor functions
const promise = new Promise((resolve, reject) => {
if (Math.random() < 0.5) {
return resolve('Success'); // Incorrect: returning a value from a Promise executor function
} else {
return reject('Failure'); // Incorrect: returning a value from a Promise executor function
}
});
-
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.
Disallow the use of the __proto__
property
const newObj = {};
newObj.__proto__ = someOtherObj;
- This rule helps enforce a best practice that avoids the direct manipulation of an object’s prototype chain using the
__proto__
property, which is a de facto standard, but not part of ECMAScript’s specification until ES2015, and then only for browser compatibility. - It aims to encourage the use of
Object.create
, a more robust and standard approach to setting an object’s prototype, promoting code consistency and adherence to modern JavaScript standards. - By disallowing the use of
__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. - The
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.
Disallow calling some Object.prototype
methods directly on objects
const myObject = {
property: "value"
};
// Using hasOwnProperty directly on an object instance
if (myObject.hasOwnProperty("property")) {
console.log("myObject has a property named 'property'.");
}
- Prevents potential errors when calling
Object.prototype
methods directly on objects that might have their own properties or methods with the same names, avoiding unexpected behavior or shadowing issues. - Increases code safety by ensuring that methods like
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. - Encourages the use of a consistent and safer approach to check object properties by leveraging
Object.prototype
directly, promoting best practices across the codebase and facilitating code readability and maintenance. - Helps to avoid issues when working with objects that might not inherit from
Object.prototype
(e.g., objects created withObject.create(null)
), thus ensuring that the checks for properties are always conducted in a reliable and error-free manner.
Disallow variable redeclaration
function calculateSum(numbers) {
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
var sum = numbers[i]; // redeclaration of `sum`
}
return sum;
}
-
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 variablesum
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.
Disallow multiple spaces in regular expressions
// Bad example violating no-regex-spaces
const regex = new RegExp("foo bar");
-
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.
Disallow specified names in exports
// Assume "temp" is a restricted name
export const temp = () => {
console.log('Do something temporary');
};
- Prevents the use of specific, perhaps confusing or deprecated, names in exports, thereby encouraging more clear or up-to-date terminologies and improving code maintainability and readability.
- Enables the restriction of default exports under certain conditions, which can help enforce a more consistent and possibly more easily understood module interface, especially in larger projects where default exports might lead to ambiguities.
- Allows project-specific customization of restricted export names, giving teams the flexibility to tailor the rule to their unique practices or to avoid naming collisions and potential bugs that might arise from shadowing or inadvertent overrides.
- Encourages a more deliberate export strategy by providing feedback when potentially problematic export names are used, fostering better coding practices by nudging developers towards making explicit and thoughtful export naming decisions.
Disallow specified global variables
function handleClick() {
console.log(event.type); // The use of the global 'event'
}
document.getElementById('button').addEventListener('click', handleClick);
- This rule helps enforce a list of restricted global variables that could potentially clash with local variables or lead to unexpected behavior if used inadvertently in a code base, improving code clarity and maintainability.
- By allowing the configuration of custom messages for each restricted global, developers can provide specific reasons or alternatives for each restriction, enhancing team communication and code readability.
- The rule promotes best practices, such as passing variables explicitly rather than relying on implicit global variables, which can make the code less prone to errors and more straightforward to understand for developers who may not be familiar with the context in which the global variables are being used.
- It aids in preventing the use of deprecated or undesired global variables that could lead to cross-browser compatibility issues or reliance on APIs that are frowned upon, encouraging the use of more robust and maintainable solutions.
Disallow specified modules when loaded by import
// This is bad because it imports from a restricted module 'lodash'
import _ from 'lodash';
const result = _.isEmpty([]);
console.log(result);
- This rule helps enforce project-specific best practices, such as avoiding importing modules that are known to be problematic, outdated, or incompatible with the project’s architecture, by specifying these modules directly within the rule configuration.
- It allows for more granular control over imports by not only specifying entire modules but also targeting specific imports from those modules, which can be useful for blocking the use of certain features from a library while allowing others.
- The rule supports custom error messages for each restricted path or pattern, enhancing the developer experience by providing clear guidance on why an import is disallowed and what alternatives, if any, are recommended.
- Pattern-based restrictions enable the blocking of imports matching a certain pattern, including support for case sensitivity and partial name matches, which is valuable for projects looking to enforce naming conventions or prevent the import of a dynamic set of modules without having to list each one explicitly.
Disallow specified modules when loaded by require
// This will trigger the no-restricted-modules rule because 'fs' is a restricted module
const fs = require('fs');
function readFile(path) {
return fs.readFileSync(path, "utf8");
}
console.log(readFile("./config.json"));
-
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.
Disallow certain properties on certain objects
// Example of using Math.pow, which we've decided to restrict
const square = Math.pow(2, 2);
const cube = Math.pow(3, 3);
console.log(square, cube);
- This rule allows teams to prevent the usage of deprecated or undesired methods and properties on objects, such as
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. - It provides a mechanism to enforce consistency across the codebase by disallowing certain properties or methods that might lead to confusion or have better alternatives. This consistency is crucial for maintainability and readability, especially in larger projects.
- The rule is configurable to target specific properties on specific objects or to globally restrict certain properties regardless of the object they belong to. This flexibility allows teams to tailor the linting to their project’s needs, focusing on the most relevant issues.
- The inclusion of custom messages for each restricted property or method aids in educating developers about why a particular usage is discouraged and suggests preferred alternatives. This educational aspect helps improve developer knowledge and code quality over time.
Disallow specified syntax
const myArray = [1, 2, 3, 4, 5];
for (const index in myArray) {
console.log(myArray[index]);
}
-
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 offor...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.
Disallow assignment operators in return
statements
function returnNextCount() {
let count = 0;
return count += 1;
}
-
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.
Disallow unnecessary return await
async function fetchData() {
return await someAsyncFunction();
}
-
The rule helps in improving code readability by avoiding redundancy. Specifically, using
return await
in an async function is redundant because theawait
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.
Disallow javascript:
urls
// This example dynamically sets a hyperlink's href attribute to execute JavaScript, which is considered unsafe.
let link = document.createElement('a');
link.setAttribute('href', 'javascript:void(0);');
document.body.appendChild(link);
-
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.
Disallow assignments where both sides are exactly the same
let a = 5;
// Erroneous self-assignment
a = a;
-
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.
Disallow comparisons where both sides are exactly the same
function checkValue(value) {
// This comparison does not make sense because it compares the variable to itself
if (value === value) {
console.log('This is always true, except for NaN values');
}
}
-
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.
Disallow comma operators
function badSequenceExample() {
let a = 1, b = 2;
a = b, b = 3; // This line uses the comma operator - it's considered bad practice under this rule.
return a + b;
}
- The
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. - This rule includes logic to allow certain uses of sequences in contexts where they are commonly accepted or where the intention is clear (e.g., within for statement updates), demonstrating that it’s tailored to enhance code clarity without being overly restrictive in scenarios where sequences are practical and intentional.
- By providing an option to allow sequences within parentheses if wrapped twice, this rule acknowledges that developers sometimes use sequences deliberately for specific effects. This option respects developer intent while still enforcing code clarity, as double parentheses indicate a clear choice rather than a possible accident.
- The rule’s ability to pinpoint the exact location of the unwanted comma operator for reporting ensures that developers can quickly identify and correct instances of its use. This precision helps maintain high code quality and adherence to best practices without unduly burdening the developer with vague or hard-to-trace error messages.
Disallow returning values from setters
class Person {
constructor(name) {
this._name = name;
}
// Bad: Setter is returning a value
set name(value) {
this._name = value;
return this._name; // This should not happen in a setter
}
}
- This ESLint rule prevents the misuse of setter functions by ensuring they do not return a value, adhering to the standard design principle of setters only modifying state without an expectation of a return value. This ensures consistency and clarity in codebases, as returning a value from a setter can lead to unexpected behavior or misunderstandings about the setter’s purpose.
- The rule specifically targets setters, employing a method to differentiate between regular functions and setter functions within its logic. This targeted approach ensures that only relevant code patterns are flagged, minimizing false positives and focusing developer attention on genuine issues related to improper setter usage.
- By reporting any return statements within setter functions, the rule directly assists in maintaining clean and idiomatic JavaScript code. It promotes best practices by encouraging developers to correct instances where a setter inadvertently returns a value, thus improving code quality and maintainability.
- The inclusion of handling for various function declarations (e.g.,
FunctionDeclaration
,FunctionExpression
, andArrowFunctionExpression
) 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.
Disallow identifiers from shadowing restricted names
function argumentsExample() {
let arguments = 5; // This shadows the `arguments` object
console.log(arguments);
}
-
This rule prevents the confusion that arises when developers redefine or shadow globally restricted names such as
undefined
,NaN
,Infinity
,arguments
, andeval
within a local scope. For instance, redefiningundefined
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 theeval
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
orNaN
, 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.
Disallow variable declarations from shadowing variables declared in the outer scope
const level = "top";
function printLevel(level) {
console.log(level); // This 'level' shadows the outer variable
}
printLevel("inner");
- The rule ensures clarity and maintainability of code by preventing confusion that arises when the same variable name is used in different scopes. By disallowing shadowing, developers can easily identify which variable is being referred to at any given point, enhancing readability and reducing the likelihood of bugs related to misidentification of variable scope.
- It provides options to customize the enforcement of the rule based on the project’s needs, such as allowing certain variable names to be shadowed, handling built-in globals, and setting hoist behavior. This flexibility allows teams to adopt the rule without completely overhauling their coding practices, especially in cases where shadowing might be intentional or considered harmless.
- The rule includes checks for various edge cases where shadowing might occur, such as within class declarations, during initialization, or in function expressions. This comprehensive approach means that it can effectively catch and prevent a wide range of shadowing issues that could lead to confusing or erroneous code behavior, providing a safeguard against subtle bugs.
- It focuses on enhancing code quality by encouraging the use of unique and descriptive variable names across different scopes. This practice not only prevents shadowing but also contributes to more self-documenting code, making it easier for new developers to understand the codebase and for teams to maintain it over time.
Disallow spacing between function identifiers and their applications (deprecated)
// There's a space between the function name and its invoking parentheses.
myFunction ();
- This rule helps maintain consistency in the codebase by enforcing a specific style for function calls, which is crucial when working in teams to ensure that the code looks uniform across different parts of the project. By disallowing spaces between function identifiers and their applications, it standardizes the appearance of function calls.
- It can prevent potential minification errors or compatibility issues in different JavaScript engines. While modern engines are likely to interpret spaced and non-spaced function calls equally, ensuring there’s no space eliminates any room for errors or discrepancies in how the code is run.
- The rule aids in the readability of the code by reducing visual clutter. Without spaces between function names and parentheses, it becomes immediately clear where a function call begins, making the code easier to scan and understand, especially for those new to a project or less experienced developers.
- Automating the removal of spaces through the provided fix function can save developer time and reduce manual code review efforts focused on stylistic concerns. This automation allows developers to focus more on logic and less on formatting, improving efficiency in the development process.
Disallow sparse arrays
// BAD: Creating a sparse array with empty slots
const badArray = [1, , , , 5];
-
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()
andforEach()
, 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.
Disallow synchronous methods
const fs = require('fs');
// Bad: using synchronous method readFileSync
try {
const data = fs.readFileSync('/path/to/file.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
-
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.
Disallow all tabs
function badExample() {
const name = "John"; // Here the indentation is done with a tab
console.log("Name:", name);
}
- This ESLint rule explicitly targets the use of tabs within code files, aiming to enforce a consistent style of indentation (spaces over tabs). This consistency ensures that code is uniformly readable across various editors, tools, and teams, reducing the chance of formatting issues that can arise from differing tab widths.
- The rule provides an option (
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. - Within its implementation, the rule leverages a regular expression to efficiently scan each line of code for tabs, and utilizes the ESLint context to report specific locations where tabs are found. This pinpoint reporting aids developers in quickly identifying and rectifying instances where tabs are used, enhancing the maintainability and readability of the code by adhering to the team’s or project’s coding standards.
- By enforcing a no-tabs policy (except potentially for indentation when configured), this rule can lead to a decrease in merge conflicts and diffs that are purely stylistic in nature. Spaces are a more deterministic way of ensuring that the visual representation of the code remains consistent across environments, thereby reducing the cognitive load on developers who no longer need to adjust to varying indentation styles within the same codebase.
Disallow template literal placeholder syntax in regular strings
const name = "John";
const greeting = "Hello, ${name}! Welcome back!";
console.log(greeting);
-
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.
Disallow ternary operators
const age = 18;
const canVote = age >= 18 ? 'Yes' : 'No';
console.log(canVote); // Output would be 'Yes' or 'No' based on the age.
- This rule ensures code readability by discouraging the use of ternary operators, which can be hard to read and understand at a glance, especially for individuals new to programming or those not familiar with the syntax.
- It promotes the use of if-else statements, which are universally understood and can make the code more accessible to developers from various programming backgrounds, enhancing maintainability.
- By disallowing ternary operators, the rule aids in preventing nested or complex conditional logic that can be difficult to debug and understand, supporting cleaner and more straightforward code structure.
- Implementing this rule can help in code review processes by standardizing the approach to conditional logic across the codebase, making it easier for reviewers to follow the logic without needing to parse through ternary expressions.
Disallow this
/super
before calling super()
in constructors
class Base {
constructor(name) {
this.name = name;
}
}
class Derived extends Base {
constructor(name, age) {
this.age = age; // Illegal use of 'this' before 'super()'.
super(name);
}
}
- Enforces the correct order of operations in constructors of derived classes, ensuring
super()
is called beforethis
is accessed, which aligns with JavaScript’s requirement for derived classes to initialize the parent class before usingthis
. This prevents runtime errors that occur whenthis
orsuper
is used beforesuper()
is called, enhancing code reliability and correctness. - Helps maintain a consistent structure in class constructors, making the code easier to read and understand. By ensuring that
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. - Increases developer awareness about the importance of the initialization order in class constructors. By reporting the incorrect use of
this
orsuper
before callingsuper()
, developers are reminded of the specific language rules related to class inheritance and constructor chaining, promoting best practices in object-oriented JavaScript programming. - Aids in automated code refactoring and review processes by providing clear, actionable feedback on constructor patterns that violate the rule. This helps in maintaining code quality and adherence to JavaScript language semantics, especially in large codebases or teams where consistency in coding styles and practices is important.
Disallow throwing literals as exceptions
// Bad: throwing a string literal
throw "Error occurred";
// Bad: throwing a numeric literal
throw 404;
// Bad: throwing a boolean
throw true;
// Bad: throwing an object literal directly
throw { message: "Error occurred", code: 500 };
- Ensures that errors thrown in JavaScript code are instances of
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. - Prevents the practice of throwing literals (like strings, numbers, or booleans) directly, which can lead to ambiguity in error handling. Since literals do not contain a stack trace or other error-related properties, diagnosing issues becomes more challenging.
- Encourages the use of more descriptive error messages by nudging developers towards the instantiation of
Error
objects with meaningful messages. This practice enhances code readability and maintainability, as it provides clearer insight into the nature of the error. - Facilitates the extension of built-in
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.
Disallow trailing whitespace at the end of lines
function sayHello() {
console.log("Hello, world!");
}
-
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.
Disallow initializing variables to undefined
// Unnecessary initialization of a variable to undefined
let myVar = undefined;
let anotherVar = undefined;
// An example within a function
function myFunction() {
let funcVar = 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 toundefined
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.
Disallow the use of undeclared variables unless mentioned in /*global */
comments
function displayUser() {
console.log(user.name); // 'user' is not defined.
}
displayUser();
-
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.
Disallow the use of undefined
as an identifier
// An example where `undefined` is used inappropriately as a variable name
let undefined = "This should not be done";
function checkValue(value) {
if (value === undefined) {
console.log("Value is undefined");
} else {
console.log("Value:", value);
}
}
checkValue("A sample value");
- By disallowing the use of
undefined
as an identifier, this rule helps maintain clarity and prevents ambiguity in codebases, ensuring thatundefined
remains a predictable, non-overridden value in JavaScript. This is particularly useful in debugging sessions where the unexpected use ofundefined
can lead to confusion. - The rule’s implementation ensures that developers do not accidentally shadow the global
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 ofundefined
is expected to be constant and unchangeable throughout the execution of the program. - It promotes better coding practices by encouraging the use of meaningful variable names and avoiding the misuse of JavaScript’s built-in values. This can lead to more readable and maintainable code as developers are pushed to find more descriptive names for their variables instead of resorting to the
undefined
keyword. - This ESLint rule aids in the enforcement of a coding standard across a development team or project, ensuring consistency in how
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.
Disallow dangling underscores in identifiers
class MyClass {
constructor(_value) {
this._value_ = _value;
}
_privateMethod() {
console.log('Doing something private...');
}
get _valueGetter() {
return this._value_;
}
static _staticMethod_() {
console.log('Static method with dangling underscores');
}
}
function _globalFunction(_param_) {
console.log('Global function with underscores', _param_);
}
const _myVariable = 'Hello, World!';
- The rule ensures consistency in naming conventions across the codebase by disallowing dangling underscores in identifiers, which can help in maintaining a clean and readable code structure, particularly important in larger projects where consistency aids in readability and maintainability.
- It allows for exceptions through options, providing flexibility to permit dangling underscores in specific cases (e.g.,
allowAfterThis
,allowFunctionParams
), thereby accommodating use cases where underscore prefixes or suffixes may be a convention or requirement, such as in certain libraries or frameworks. - By supporting configuration options like
enforceInMethodNames
andenforceInClassFields
, 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. - The rule’s capability to differentiate between variable declarations, functions (including parameters), class properties, and methods ensures that the enforcement of the naming convention is comprehensive and applies to a wide range of identifier types, thereby ensuring a uniformly enforceable style across different aspects of the codebase.
Disallow confusing multiline expressions
const value = "Hello, World"
[1, 2, 3].forEach(console.log)
- This rule specifically addresses and prevents confusion that may arise from JavaScript’s automatic semicolon insertion (ASI) mechanism, where semicolons are automatically inserted at the end of lines if they are not manually placed by the programmer. The given “bad” example shows how omitting a semicolon can lead to unexpected behavior, thinking the array is part of the previous statement.
- It ensures clear distinction and readability between statements and expressions by enforcing the placement of semicolons where necessary. In multiline scenarios, where expressions might span over several lines, it helps to clearly identify the end of one expression and the beginning of another, as showcased in the “fix” example.
- By targeting specific patterns like member expressions, tagged template expressions, call expressions, and certain binary expressions, it provides tailored feedback to developers about where exactly the confusion might arise, allowing them to correct their code in very specific ways. This rule does not broadly apply but selectively applies to patterns that are highly susceptible to multiline confusion.
- It promotes best practices in coding style, indirectly encouraging developers to write more maintainable and less error-prone code. By catching potential ambiguities early in the development process, it helps to prevent runtime errors or bugs that might be hard to trace back to their origin, demonstrating the importance of the rule in maintaining code quality and ensuring consistent code behavior.
Disallow unmodified loop conditions
function checkPassword(inputs) {
let attempts = 0;
const maxAttempts = 3;
while (attempts < maxAttempts) {
// Assuming checkInput is a function that validates the input and returns true or false
if (checkInput(inputs[attempts])) {
console.log("Access Granted.");
break;
}
// attempts variable is not modified inside the loop, it can potentially lead to an infinite loop
}
console.log("Access Denied.");
}
-
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 ifcheckInput
never returnstrue
. -
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.
Disallow ternary operators when simpler alternatives exist
var isAdult = age >= 18 ? true : false;
- The rule discourages redundant use of ternary operators, promoting code readability and simplicity by suggesting the direct use of the condition itself when the ternary operator returns a boolean value. For example, replacing
age >= 18 ? true : false
with a simplerage >= 18
. - It helps in identifying and auto-correcting ternary expressions that are unnecessarily complex, leading to cleaner and more efficient code. Such as transforming
foo ? true : false
into justfoo
or!!foo
depending on whetherfoo
is guaranteed to be a boolean expression, making the intention clearer and the code shorter. - The rule includes facilities for fixing common patterns that misuse ternary operators, like turning an identity check followed by a default assignment (
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. - By offering fixes that invert expressions or replace unnecessary conditional expressions with their simpler equivalents, it not only optimizes the code but also educates developers about better coding practices specific to conditional logic. This is particularly useful for those who might not be fully aware of JavaScript’s truthy/falsy semantics or the capabilities of logical operators, improving code quality over time as developers learn to avoid these patterns.
Disallow loops with a body that allows only one iteration
function checkUnreachableLoop() {
for (let i = 0; i < 10; i++) {
console.log("This loop will only run once");
break;
}
}
-
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.
Disallow unreachable code after return
, throw
, continue
, and break
statements
function exampleFunction() {
return "This is returned";
console.log("This message will never be logged");
}
-
The rule specifically targets and eliminates unreachable code that follows
return
,throw
,continue
, andbreak
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.
Disallow control flow statements in finally
blocks
function checkData(data) {
try {
// Attempt to parse JSON
return JSON.parse(data);
} catch (e) {
// Handle JSON parsing error
throw new Error('Failed to parse data');
} finally {
// Incorrect: Using a return statement in the finally block
return "This could lead to unexpected behavior.";
}
}
-
Ensures predictability in error handling: Using control flow statements like
return
,throw
,break
, andcontinue
infinally
blocks can lead to unpredictable behavior and override the error handling or response from thetry
orcatch
blocks. This rule helps maintain the intended flow of execution, ensuring that any cleanup in thefinally
block doesn’t inadvertently change the outcome of thetry-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 infinally
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 intry
orcatch
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 afinally
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 withinfinally
blocks, this rule promotes the correct use offinally
blocks for their intended purpose, ensuring that they are used to safely and reliably clean up after atry-catch
block without interfering with the function’s outcome.
Disallow negating the left operand of relational operators
if (!key in object) {
// This will not check if 'key' is not in 'object';
// instead, it will check if 'false' is in 'object' because `!key` gets evaluated first.
}
-
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 iffalse
is inobject
, not ifkey
is not inobject
. -
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.
Disallow use of optional chaining in contexts where the undefined
value is not allowed
// Bad: Using optional chaining in arithmetic operation
const obj = { a: 5 };
const result = obj?.b + 5; // Could result in `undefined` + 5
// Bad: Using optional chaining in logical operation without considering undefined
const value = obj?.c || 'default'; // Could result in `undefined` || 'default'
-
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 inundefined + 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 handleundefined
andnull
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.
Disallow unused expressions
function potentiallyUnusedExpression() {
"use strict";
0; // This expression has no effect and will be flagged by `no-unused-expressions`
true; // Similarly, this boolean literal does nothing and will be flagged
someFunction; // This references a function without calling it, doing nothing effective.
}
- The rule helps prevent potential bugs that can occur from expressions that execute without affecting the program’s state, such as a function reference without a call or a standalone numerical literal, which could indicate a missing or misplaced operation.
- It encourages clear and intentional coding practices by flagging expressions that seemingly have no effect, pushing developers to either remove unnecessary code or rewrite it in a manner that clearly expresses its intention, thus improving code readability and maintainability.
- By providing configuration options such as
allowShortCircuit
,allowTernary
, andallowTaggedTemplates
, 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. - The rule supports modern JavaScript syntax and constructs, including ES6 features and JSX, making it applicable and beneficial to a wide variety of JavaScript projects, including web applications that use frameworks like React. This ensures that projects using advanced features can still enforce best practices regarding unused expressions.
Disallow unused labels
function checkUnusedLabel() {
loop: for (let i = 0; i < 5; i++) {
console.log(i);
}
}
- The given ESLint rule specifically targets the elimination of unused labels in the code, which can lead to clearer, more maintainable JavaScript by removing unnecessary elements that do not contribute to the program’s logic or functionality. Unused labels can be confusing to developers, suggesting a complexity or control flow that does not actually exist.
- By providing a fixable mechanism for removing these labels when they are determined to be safe to remove (ensuring no comments are in between the label and its body, and that removing the label does not inadvertently alter the program’s logic), the rule aids in automatically refactoring code. This automation helps maintain code quality without requiring manual intervention, thereby saving time and reducing the likelihood of human error.
- The rule incorporates logic to check whether removing a label could potentially turn the following statement into a directive (e.g., a string that could be interpreted as a “use strict” directive). This nuanced approach ensures that the rule does not inadvertently alter the semantic meaning of the program, demonstrating its careful design to only apply fixes when they are guaranteed not to introduce bugs.
- By marking labels as used when they are referenced in break or continue statements within their scope, the rule provides a context-aware evaluation of label usage. This approach ensures that labels are only reported as unused if they truly are not referenced anywhere within their accessible scope, thus preventing false positives and ensuring the rule accurately identifies genuinely unused labels.
Disallow unused private class members
class MyClass {
#unusedPrivateMethod() {
console.log('This method is private and unused.');
}
publicMethod() {
console.log('This method is public and used.');
}
}
-
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.
Disallow unused variables
function myFunction() {
let unusedVariable = 'I am not used';
const anotherUnused = 42;
console.log('This function does something but does not use the declared variables');
}
myFunction();
- The rule helps in identifying and removing variables that are declared but never used within the code, which leads to cleaner, more readable, and efficient codebases by eliminating dead code.
- It provides configurable options for different scenarios such as ignoring variables in destructuring, parameters, and catch clauses based on patterns, enabling teams to tailor the rule to their project’s guidelines and practices.
- By specifically targeting unused variables in different contexts (e.g., function arguments, catch errors) and allowing ignore patterns, it avoids false positives and offers flexibility in identifying genuinely unused variables versus those that are intentionally left for future use or clarity.
- The detailed reporting mechanism that distinguishes between variables that have been “defined and unused” versus “assigned a value and unused” helps in easier understanding and rectification of issues, guiding developers towards precise code maintenance activities.
Disallow the use of variables before they are defined
function myFunction() {
console.log(helloWorld()); // Error: 'helloWorld' was used before it was defined
}
const helloWorld = () => {
return "Hello, world!";
}
-
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.
Disallow useless backreferences in regular expressions
const regex = /^(a)\1$/;
- The rule identifies and reports backreferences that refer to groups that cannot logically be matched at the point the backreference is evaluated, helping to avoid complex and potentially incorrect regular expressions. This specific attention to the logic of group matching relative to backreferences ensures that developers can write more maintainable and less error-prone code.
- By flagging nested, forward, backward, and disjunctive backreferences and those inside a negative lookaround, the rule helps in optimizing regular expressions for better performance and readability. For instance, it could prevent the use of a backreference that will always fail due to its position relative to the referenced group, guiding developers toward more straightforward and efficient regex patterns.
- The rule’s automatic detection and reporting mechanism provides immediate feedback on regex patterns that contain useless backreferences, which can be an educational tool for developers to learn about regex intricacies and avoid common pitfalls associated with backreferences in regex.
- The ability to refactor flagged regular expressions to a recommended format, as exemplified by the replacement of
^(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.
Disallow unnecessary calls to .call()
and .apply()
function greet(name) {
console.log(`Hello, ${name}!`);
}
// Unnecessary use of .call()
greet.call(null, 'John Doe');
// Unnecessary use of .apply()
greet.apply(null, ['Jane Doe']);
-
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 alteredthis
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 thethis
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 thethis
binding or passing an array of arguments is truly needed, fostering better coding habits.
Disallow unnecessary catch
clauses
try {
doSomethingThatMightFail();
} catch (error) {
throw error; // This catch is unnecessary.
}
- The rule efficiently identifies catch clauses that simply re-throw the caught error without performing any actual error handling. This ensures that try-catch blocks are used meaningfully, contributing to cleaner, more understandable code.
- By discouraging the use of unnecessary catch clauses, this rule guides developers towards more purposeful error handling strategies. This not only aids in debugging but also encourages the implementation of robust error recovery mechanisms.
- It helps in reducing the boilerplate code, making the codebase more concise and maintainable. Catch clauses that merely throw the caught exception again add to the code size without providing any real value, and identifying these can streamline the code.
- This rule prompts a review of error handling logic, potentially uncovering more subtle logic errors or misunderstandings about how exceptions work in JavaScript. For example, a developer might mistakenly believe they are transforming the error or enriching it with more information when, in reality, they’re not adding any value by catching and re-throwing the same error.
Disallow unnecessary computed property keys in objects and classes
// Unnecessary computed keys in an object
const object = {
['name']: 'John Doe',
['age']: 30
};
// Class with unnecessary computed keys
class MyClass {
constructor() {
this['data'] = {};
}
['getData']() {
return this.data;
}
}
-
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.
Disallow unnecessary concatenation of literals or template literals
const greeting = "Hello, " + "world!";
-
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.
Disallow unnecessary constructors
class ParentClass {
constructor(name) {
this.name = name;
}
}
class ChildClass extends ParentClass {
constructor(name) {
super(name); // Unnecessary constructor
}
}
- This ESLint rule specifically identifies and reports constructors within classes that do nothing more than forwarding the arguments to the parent class’s constructor or are entirely empty. It helps in reducing the verbosity and redundancy of the code, making it cleaner and easier to read.
- By detecting unnecessary constructors, this rule indirectly encourages developers to rely on the default constructor behavior of JavaScript classes, which can lead to a better understanding of the language’s prototypal inheritance and how constructors work, especially in the context of class inheritance.
- Implementing this rule can lead to minor performance improvements in some scenarios. Removing redundant constructors eliminates the unnecessary function calls during the instantiation of objects, which, although not significantly impactful in most cases, contributes to more efficient code execution.
- The rule is particularly considerate of different JavaScript parsers, such as those for TypeScript and Flow, which may not require a constructor to have a body. This compatibility feature ensures that the rule can be applied in various development environments without causing unintended syntax or compilation errors, enhancing its utility across different JavaScript-based projects.
Disallow unnecessary escape characters
// A string with unnecessarily escaped characters
const myString = "This is a bad example with a useless \\";
// A regular expression with an unnecessary escape
const myRegExp = /\d\.\d/;
- This ESLint rule helps improve code readability by highlighting and suggesting the removal of unnecessary escape characters, which might otherwise suggest a special character is being used when it’s actually not. For example, removing a needless escape in a string literal simplifies understanding of the string content.
- The rule aids in maintaining consistency across codebases, especially in environments where multiple developers work. Standardizing the usage of escape characters ensures that all escape sequences are meaningful and required.
- By eliminating superfluous escapes, this rule may indirectly prevent future errors. Developers might infer incorrect functionality or special handling from unnecessary escaped characters, leading to potential misunderstandings or bugs when modifying the code.
- The rule provides actionable suggestions for both removing unnecessary escapes and, when applicable, escaping backslashes correctly. This not only educates developers on the proper use of escape characters within string literals and regular expressions but also facilitates quick fixes, thus streamlining the development process.
Disallow renaming import, export, and destructured assignments to the same name
// Unnecessary renaming in import
import { foo as foo } from 'module';
// Unnecessary renaming in export
export { bar as bar };
// Unnecessary renaming in destructured assignment
const { baz: baz } = myObject;
-
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.
Disallow redundant return statements
function exampleFunc(value) {
if (value) {
return true;
}
return; // This return is unnecessary
}
-
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.
Require let
or const
instead of var
var name = "John Doe";
for (var i = 0; i < 5; i++) {
console.log(i);
}
console.log("Outside loop:", i); // i is accessible here because it was declared with var
-
Promotes block-scoped variable declarations: This rule enforces the use of
let
orconst
for variable declarations, which are block-scoped, as opposed tovar
, 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 ofvar
, 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
andconst
have TDZ constraints, this rule helps in identifying potential reference errors caused by accessing alet
orconst
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
tolet
orconst
(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.
Disallow void
operators
const result = void someFunctionThatReturnsValue();
function avoidLeak(){
void fetchData(); // Incorrect: `void` is used here to ignore a promise or expression result.
}
- This rule helps in maintaining readability and standard coding practices by discouraging the use of the
void
operator. By preventingvoid
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. - It promotes the explicit handling of functions or promises, as seen in the provided examples. Instead of using
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. - The rule can help in avoiding certain anti-patterns, like using
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. - The flexibility offered by the
allowAsStatement
option within the rule allows teams to enforce this rule while still permittingvoid
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 usevoid
in a restricted, perhaps more controlled manner.
Disallow specified warning terms in comments
// TODO: Implement the function logic
function add(a, b) {
// FIXME: handle edge cases
return a + b;
}
- The rule specifically targets comments containing terms like “TODO”, “FIXME”, or “XXX”, which are commonly used to denote work that needs to be revisited. Enforcing this rule helps in ensuring that such placeholders do not get overlooked and are adequately addressed before code is deployed or progresses further in the development cycle.
- By allowing configuration of the warning terms and their locations within the comments (whether at the start or anywhere), this rule provides flexibility to adapt to different coding standards or conventions within a team or project. This adaptability ensures that teams can enforce the rule without hindering their specific workflow or comment notation preferences.
- The inclusion of case-insensitive and Unicode case folding in the regular expression matching process makes this rule robust against variations in how developers might write warning comments. This minimizes the risk of missing warning comments due to differences in case or the use of Unicode characters, thereby improving the thoroughness of the code review process.
- The rule’s mechanism to report the exact warning term found in a comment, as well as a portion of the comment itself (with a safeguard to limit the reported length), provides clear and actionable feedback to developers. This specificity helps in quickly identifying and addressing the flagged issues without the need for extensive manual searching through the codebase, thereby streamlining the code review and maintenance process.
Disallow whitespace before properties
let obj = { a: 1, b: 2 };
// There is an unexpected whitespace before the property 'a'.
console.log(obj .a);
// Another example with more complex property access and whitespace
let arr = [1, 2, 3];
console.log(arr [2]);
-
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
orarray [index]
intoobject.property
orarray[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.
Disallow with
statements
let obj = {a: 1, b: 2, c: 3};
with (obj) {
console.log(a); // Intended to log obj.a
console.log(b); // Intended to log obj.b
}
- The rule helps in maintaining consistent code readability by discouraging the use of
with
statements, which can make it harder to determine where variables are coming from, especially in larger code bases. - By disallowing
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. - It aids in preventing potential runtime errors and debugging difficulties that can arise from the ambiguous scope introduced by
with
statements, which can lead to mistaken assumptions about the existence or value of variables. - Since
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.
Enforce the location of single-line statements
if (condition) console.log('This is on the same line.');
-
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.
Enforce consistent line breaks after opening and before closing braces
const user = {name: 'John', age: 30, city: 'New York'};
- Enhances code readability and maintainability by enforcing a consistent code formatting style, specifically regarding the use of line breaks after opening and before closing braces, making the code easier to scan visually.
- Reduces the risk of merge conflicts in team environments by standardizing the formatting of object literals, import declarations, and export declarations, which are common sources of formatting discrepancies.
- Aids in quickly identifying errors related to incorrect object property alignment and misplaced braces by providing visual cues through consistent formatting, thus potentially reducing debugging time.
- Includes options for fixing detected issues automatically, sparing developers from manual corrections and ensuring quick compliance with the rule, improving overall development efficiency.
Enforce consistent spacing inside braces
const obj = {foo: 'bar'};
const {a,b} = obj;
function example({param1,param2}) {
console.log(param1, param2);
}
import {module1,module2} from 'module';
-
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.
Enforce placing object properties on separate lines
const user = { name: 'John Doe', age: 30, isAdmin: false };
- The rule enhances readability by ensuring that properties of an object are easily distinguishable, making it simpler for developers to identify and understand each property’s purpose without the need to parse through a single, potentially long line of code. This is particularly beneficial in cases where objects have multiple properties.
- It aids in version control practices by minimizing merge conflicts. Since each property is on its own line, changes made to one property are less likely to interfere with changes made to another, compared to objects with all properties on the same line.
- The rule supports the automatic fixing of formatting issues that do not adhere to the specified style, thereby reducing manual efforts in code reviews and maintaining consistency across the codebase without requiring developers to manually adjust each object’s formatting.
- By allowing configurable exceptions through options like “allowAllPropertiesOnSameLine”, it provides flexibility to accommodate different coding styles and preferences, ensuring that teams can apply this rule without disrupting their established workflows or preferences regarding object property formatting.
Require or disallow method and property shorthand syntax for object literals
// Disallowed shorthand for object properties
const name = "John Doe";
const age = 30;
const person = {
name: name,
age: age
};
- Encourages a consistent code style by either enforcing or disallowing the use of shorthand syntax for methods and properties in object literals, which helps in maintaining a uniform codebase that is easier for team members to read, understand, and maintain.
- Enhances code readability and succinctness by allowing developers to use shorthand for properties and methods when possible, leading to a more concise and readable code structure without the redundancy of repeating property names.
- Offers configurability for different coding styles, such as always enforcing shorthands, never using them, applying them only to properties or methods, or ensuring consistency across an object, which allows teams to adopt a style that matches their preferences or project guidelines.
- Provides automated fix suggestions to convert between shorthand and longform as per the configured rule, aiding developers in quickly conforming to the coding standards without manually rewriting parts of the code, thus saving time and reducing the likelihood of errors during refactoring.
Require or disallow newlines around variable declarations
function demoFunction() {
let x = 1, y = 2;
const a = 3, b = 4;
}
- This rule directly contributes to improving code readability by ensuring that each variable declaration is visually separated. This separation allows developers to quickly identify and assess variables individually, reducing the cognitive load when scanning through the code.
- By enforcing newlines around variable declarations, it helps in maintaining a consistent code style throughout the project. Consistency is key in making the codebase more approachable to new developers and maintaining it over time, as it reduces the effort needed to understand different parts of the project.
- The explicit separation of variable declarations can lead to better version control practices. When variables are declared on separate lines, changes to one variable result in a diff for that line only, making it easier for developers to understand what was changed in a commit and why it was changed, thus improving the code review process.
- It aids in reducing errors during code modification or refactoring. When variables are declared on separate lines, the risk of accidentally modifying or deleting part of a variable declaration is reduced. This can be particularly useful in dynamically typed languages where such errors might not be caught until runtime.
Enforce variables to be declared either together or separately in functions
function demoFunc() {
let a = 1;
let b = 2;
}
- The rule enforces a consistent variable declaration strategy within functions, which can aid in maintaining a uniform coding style across a codebase. By either combining variable declarations or requiring them to be separate, the rule helps in making the code more readable and organized according to the team’s preferences.
- It provides automatic fix capabilities to adjust variable declarations to comply with the configured mode—
always
,never
, orconsecutive
. This feature can save developers time during refactoring and help new team members adhere to project standards without manually adjusting each declaration. - By allowing configuration for uninitialized and initialized variables separately, and the option to handle
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. - It helps in identifying and preventing mixed variable declarations within the same scope. For example, the rule can flag a block where variables are both combined and separately declared, urging a uniform approach. This prevents potential confusion and aids in maintaining a clean code structure, especially important in larger or more complex functions where variable declarations can significantly impact readability and maintainability.
Require or disallow assignment operator shorthand where possible
// Example: 1 Bad usage without operator shorthand
let x = 10;
x = x + 2;
// Example: 2 Bad usage without operator shorthand
let y = 5;
y = y * 3;
// Example: 3 More complex bad usage without shorthand
let z = 4;
z = z % 2;
-
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 likex = x + 1
tox += 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 froma *= 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.
Enforce consistent linebreak style for operators
// Violates `operator-linebreak` rule when it's set to "after"
const result = condition
? option1
: option2;
let sum = a +
b +
c;
if (a
&& b
&& c) {
// Do something
}
- Enforces a specific linebreak style for operators, which improves readability by maintaining a consistent visual structure across the codebase, making it easier for developers to follow and understand the logic of expressions.
- Offers customizable settings, allowing teams to adopt a style that fits their preference (e.g., placing the operator before or after the linebreak), and even override these settings for specific operators, fostering a flexible yet standardized coding environment.
- Includes autofix functionality that can automatically correct inconsistencies detected by the rule, saving developers time during the code review and refactoring processes, and helping maintain code quality without manual intervention.
- Helps avoid syntax and logical errors that may arise from misinterpreting the operators in complex expressions by ensuring the operators are placed in a predictable position, thus enhancing code safety and reducing the potential for bugs.
Require or disallow padding within blocks
function sayHello(name) {
if (name) {
console.log(`Hello, ${name}!`);
}
}
-
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.
Require or disallow padding lines between statements
function demoFunction() {
let x = 10;
console.log(x);
if (x > 5) {
console.log("x is greater than 5");
}
return x;
}
-
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.
Require using arrow functions for callbacks
setTimeout(function() {
console.log('This callback should be an arrow function.');
}, 1000);
- Enforces consistency in code by requiring callbacks to be arrow functions, which can improve readability and reduce code complexity, specifically in cases where
function
expressions are used unnecessarily. - Arrow functions inherently bind the
this
context of the enclosing scope, which mitigates common pitfalls associated withthis
in callback functions, especially for beginners not familiar with function binding or the behavior ofthis
in JavaScript. - Supports options to allow exceptions, such as allowing named functions or functions where
this
binding is necessary and cannot be achieved through arrow functions, providing flexibility in enforcing this rule to accommodate different coding styles and requirements. - Automates refactoring through fixable examples, offering developers immediate feedback and assistance in code migration towards using arrow functions, thereby speeding up the modernization of legacy code bases or ensuring new code conforms to contemporary JavaScript standards.
Require const
declarations for variables that are never reassigned after declared
let score = 10;
console.log(score);
- Encourages the use of
const
overlet
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. - The rule helps in identifying places in the code where destructuring assignments can be optimized by suggesting the use of
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. - The rule’s logic to not automatically fix declarations unless it’s safe to do so (e.g., all variables in the declaration are initialized, it’s not in a for-in or for-of loop, or when specific conditions around destructuring are met) prevents potential breaking changes in the code. This cautious approach ensures that auto-fixes do not introduce errors or change the logic of the program.
- By offering an auto-fix option under safe circumstances, this rule simplifies the process of adopting best practices around variable declarations and reduces manual code review efforts. It enables developers to quickly align their code with best practices regarding variable use in JavaScript, thereby enhancing code maintainability and readability.
Require destructuring from arrays and/or objects
// Extracting properties from an object
const user = {
firstName: 'John',
lastName: 'Doe'
};
const firstName = user.firstName;
const lastName = user.lastName;
// Extracting elements from an array
const fruits = ['Apple', 'Banana', 'Cherry'];
const firstFruit = fruits[0];
const secondFruit = fruits[1];
- This rule promotes code readability and maintainability by encouraging the use of destructuring syntax, which allows for extracting multiple properties from an object or elements from an array in a single statement rather than doing it one by one.
- It helps in reducing the amount of boilerplate code, especially in scenarios where multiple properties need to be extracted from an object or multiple elements from an array, thereby making the code cleaner and easier to understand at a glance.
- The rule includes options for customization based on specific needs such as enforcing destructuring for renamed properties, giving flexibility to cater to various coding standards and preferences within different projects.
- By providing an automated way to enforce this style through the potential for auto-fixing simple cases, developers can ensure consistency across the codebase without manually addressing each instance, hence speeding up the development process and reducing the chance for human error.
Disallow the use of Math.pow
in favor of the **
operator
// Calculation of the square of a number using Math.pow
const square = Math.pow(4, 2);
// Calculation of the cube of a number using Math.pow
const cube = Math.pow(5, 3);
- Encourages the use of the more modern and concise
**
exponentiation operator over the verboseMath.pow
function, aligning with contemporary JavaScript practices for readability and succinctness. - Facilitates easier to read and more expressive code, especially in complex mathematical expressions, by clearly indicating exponentiation without the need for calling a function, thus reducing cognitive load for readers.
- Prevents potential performance implications of using
Math.pow
, as native operators like**
are often better optimized by JavaScript engines than equivalent method calls. - Includes a mechanism to safely refactor existing
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.
Enforce using named capture group in regular expression
const datePattern = /(\d{4})-(\d{2})-(\d{2})/;
const match = datePattern.exec('2023-04-01');
if (match) {
const year = match[1];
const month = match[2];
const day = match[3];
console.log(`Year: ${year}, Month: ${month}, Day: ${day}`);
}
- Enhances code readability and maintenance by requiring regular expressions to use named capturing groups, making it clearer what each part of the regex is intended to match or extract from the string.
- Helps prevent errors that might occur when the regex pattern is modified. When unnamed groups are used, changing the order of groups or adding new ones might require updating all index-based references, which is error-prone. Named groups avoid this issue since the reference names don’t change with their order.
- Improves the documentation aspect of the code. When a regular expression uses named capture groups, it serves as a form of inline documentation by explicitly stating the purpose of each group, aiding both in code review and future maintenance.
- Facilitates easier refactoring and debugging, as developers can see at a glance the purpose of each part of a complex regular expression. When debugging or modifying the regex, having descriptive names for each capturing group can significantly reduce the cognitive load, making it easier to diagnose issues or understand the regex’s behavior.
Disallow parseInt()
and Number.parseInt()
in favor of binary, octal, and hexadecimal literals
// Converting binary string to number using parseInt
const binaryStringToInt = parseInt('110111', 2);
console.log(binaryStringToInt); // 55
-
This ESLint rule encourages the use of binary, octal, and hexadecimal literals instead of
parseInt()
orNumber.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 inparseInt()
. 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.
Disallow use of Object.prototype.hasOwnProperty.call()
and prefer use of Object.hasOwn()
const myObject = { myProperty: "value" };
if (Object.prototype.hasOwnProperty.call(myObject, "myProperty")) {
console.log("myObject has a property named myProperty.");
}
-
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 thanObject.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 thethis
binding in thehasOwnProperty
method call, and improves readability by using a static method directly on theObject
class, making the intention of the code more immediately clear to readers.
Disallow using Object.assign with an object literal as the first argument and prefer the use of object spread instead
const target = { a: 1 };
const source = { b: 2 };
const result = Object.assign({}, target, source);
console.log(result); // output would be: { a: 1, b: 2 }
-
Ensures modern JavaScript syntax is used: By preferring the use of object spread (
{...obj}
) overObject.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.
Require using Error objects as Promise rejection reasons
function getUser(id) {
return new Promise((resolve, reject) => {
if (id <= 0) {
reject("Invalid ID"); // Rejecting with a string instead of an Error object
} else {
resolve({ id: id, name: "John Doe" });
}
});
}
getUser(-1).catch(error => {
console.log(error);
});
- Promotes the use of Error objects when rejecting Promises, ensuring that all rejections provide a consistent interface for error handling. This allows for better predictability and standardization in codebases, making debugging and error tracking more straightforward.
- Enhances stack traceability for debugging purposes. By requiring an Error object as the rejection reason, developers are provided with a stack trace that can be used to pinpoint the origin of the error, unlike primitive values like strings that offer no stack information.
- Encourages better error information encapsulation. Error objects can carry additional information about the error, including name, message, and custom properties. This comprehensive detail aids in more effective error analysis and handling compared to primitive values which are limited in the context they can convey.
- Aids in aligning with common JavaScript practices and standards. Using Error objects for rejections is a widely accepted best practice in JavaScript development. This rule helps enforce this practice, potentially reducing the learning curve for new developers by promoting consistency with broader JavaScript coding standards.
Require Reflect
methods where applicable
let obj = {};
Object.defineProperty(obj, 'property', {
value: 42
});
delete obj.property;
console.log(Object.getOwnPropertyDescriptor(obj, 'property'));
-
Encourages the use of
Reflect
API for operations likeapply
,call
,defineProperty
etc., which is designed to provide a more standardized and cleaner way to perform these operations as compared to their traditional counterparts inObject
andFunction.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
andObject.defineProperty
. For example,Reflect.apply
andReflect.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
vsdelete
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 ofReflect
is encouraged without being overly restrictive.
Disallow use of the RegExp
constructor in favor of regular expression literals
const pattern = 'abc';
const flags = 'i';
const regex = new RegExp(pattern, flags);
- This rule encourages the use of regular expression literals over the
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. - It enforces consistency in the way regular expressions are defined and used across the codebase. By preferring regex literals, developers can avoid the mix of
RegExp
constructor calls and regex literals, leading to more uniform code. - The rule helps in identifying unnecessarily wrapped regex literals, which can be an indication of redundant or overly complicated code. It suggests using a direct regex literal instead when the arguments to the
RegExp
constructor are static strings, thereby simplifying the syntax. - It also includes logic to verify that the regex patterns and flags are valid for the ECMAScript version specified in the project’s ESLint configuration. This preventive measure ensures that the regular expressions will work as expected across different JavaScript environments, avoiding runtime errors due to invalid syntax or unsupported flags.
Require rest parameters instead of arguments
function concatenate() {
let result = '';
for (let i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
}
- This rule enforces the use of rest parameters for functions which improves readability and maintainability of the code by clearly indicating that the function can accept any number of arguments. Using
...args
is more explicit than the vaguearguments
object, making the developer’s intention clearer. - It promotes the use of modern JavaScript syntax, as rest parameters are part of the ES6 specification. Adopting modern practices can aid in keeping the codebase up-to-date and encourage the use of newer language features which are often more efficient and provide cleaner syntax.
- By replacing
arguments
with rest parameters, it helps avoid the common pitfalls associated with thearguments
object, such as its non-Array nature. Thearguments
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. - This rule can improve performance in cases where the
arguments
object is used improperly. For example, passingarguments
directly to another function can lead to deoptimizations in some JavaScript engines because the engine can’t as easily optimize the passing ofarguments
due to its dynamic nature. Rest parameters do not have this issue as they are treated as any other parameter.
Require spread operators instead of .apply()
function concatenateItems(array1, array2) {
return array1.concat.apply(array1, array2);
}
const array1 = [1, 2];
const array2 = [3, 4];
const result = concatenateItems(array1, array2);
console.log(result); // Expected output: [1, 2, 3, 4]
- The rule promotes the use of modern JavaScript syntax by encouraging the spread operator over the
apply()
method. This ensures codebases stay up-to-date with the latest JavaScript features, improving readability and maintainability. - By requiring the spread operator instead of
.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 rule can aid in preventing potential issues arising from the
this
context in.apply()
calls. Since the spread operator does not involve explicitly bindingthis
, it reduces the likelihood of errors related to incorrectthis
bindings, making it safer to use. - Encouraging the spread operator aligns with functional programming principles by promoting immutability. Unlike
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.
Require template literals instead of string concatenation
let firstName = "John";
let lastName = "Doe";
let fullName = "Your full name is: " + firstName + " " + lastName + ".";
-
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 + "."
intoYour 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.
Require quotes around object literal property names
const person = {
firstName: "John",
"lastName": "Doe",
age: 30
};
-
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.
Enforce the consistent use of either backticks, double, or single quotes
// Using double quotes inconsistently with single quotes when single quotes are preferred
let greeting = "Hello, world!";
let farewell = 'Goodbye, world!';
- Enforces coding consistency, which is helpful in projects where multiple developers work together. This specific rule requires developers to use a consistent style of quotes (
backticks
,double
, orsingle
quotes) throughout the codebase, reducing the cognitive load when reading and understanding code. - Helps prevent errors related to quote mismatch by ensuring that the chosen style of quotes is used consistently. This can be especially important in languages like JavaScript where different types of quotes have different functionalities (e.g., template literals with backticks).
- The rule supports configuration options to allow exceptions in cases where avoiding escape is necessary (avoidEscape), or where template literals are beneficial for readability and functionality (allowTemplateLiterals). This flexibility supports maintaining code readability and developer preference, while still enforcing overall consistency.
- It includes logic to handle special cases such as JSX syntax and directive prologues, ensuring that the rule doesn’t disrupt the intended functionality or readability of the code in these contexts. By taking into consideration the use cases of JSX attributes, directive prologues, and the use of template literals that leverage JavaScript expressions, the rule smartly applies the appropriate style of quotes without hampering the syntactical and functional aspects specific to these cases.
Enforce the consistent use of the radix argument when using parseInt()
const inputString = "071";
const result = parseInt(inputString);
console.log(result); // Depending on the environment, this may log 57 (interpreted as octal) or 71 (interpreted as decimal)
-
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.
Disallow assignments that can lead to race conditions due to usage of await
or yield
async function updateValue() {
let value = 1;
value = await getValue() + value;
}
async function getValue() {
// Simulate an async operation, like fetching from a database
return Promise.resolve(2);
}
- Prevents potential race conditions in asynchronous code by ensuring that updates to variables are not interleaved with
await
oryield
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 anawait
oryield
could lead to outdated values being used. - Enhances code reliability and predictability by enforcing atomic updates. By requiring developers to handle asynchronous operations more carefully (e.g., by storing results of
await
expressions in temporary variables before using them in further calculations), the rule helps maintain the integrity of variable values throughout the execution flow. - Reduces bugs stemming from complex asynchronous logic by making it easier to reason about the order of operations and the state of variables at any given time. This is particularly beneficial in environments where concurrency is a common concern, and variables may be accessed or modified in multiple places.
- Improves code maintainability and readability by encouraging patterns that clearly separate asynchronous data retrieval from its usage. This separation not only helps prevent race conditions but also makes the code easier to understand and modify, as the operations leading to the final value of a variable are more linear and less intertwined with asynchronous logic.
Disallow async functions which have no await
expression
// An async function with no await, violating the `require-await` rule
async function fetchData() {
return fetch('https://example.com/data');
}
-
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 comments
function sum(a, b) {
return a + b;
}
- This rule ensures that JSDoc comments are present for
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. - It offers flexibility by allowing customization through options for other types of declarations like
MethodDefinition
,ClassDeclaration
,ArrowFunctionExpression
, andFunctionExpression
. 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. - The rule aids in automatically identifying undocumented code during the development process by reporting missing JSDoc comments. This real-time feedback loop can help maintain a high standard of code quality and ensure that documentation is not overlooked.
- By providing an option to enforce documentation on
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.
Enforce the use of u
or v
flag on RegExp
const pattern = /\w+/;
- Ensures the RegExp constructors or literals explicitly define their handling of Unicode characters, promoting consistency and clarity about whether or not the pattern should be interpreted in a Unicode-aware manner. This is particularly important for codebases that handle internationalization where Unicode characters are common.
- Prevents subtle bugs that can arise when regular expressions are used on Unicode strings without the appropriate flag, such as failing to match characters outside the Basic Multilingual Plane (BMP) correctly. By requiring the
u
orv
flag, developers are made aware of and encouraged to consider these Unicode-specific behaviors. - Provides automatic fix suggestions to help developers quickly adhere to this rule without having to manually insert the flag, enhancing productivity and reducing the likelihood of oversight. This is particularly beneficial in large codebases where manual verification and correction would be time-consuming.
- Encourages developers to be explicit about their intent regarding the handling of Unicode sequences in regular expressions, leading to more readable and maintainable code. By requiring the
u
orv
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 generator functions to contain yield
function* fetchData() {
console.log('Fetching data...');
// Missing yield statement
}
- Ensures that generator functions fulfill their intended purpose by utilizing the
yield
keyword, promoting correctness in asynchronous or iterable operations. - Prevents writing generator functions that behave like regular functions, which can lead to confusion and potential misuse in codebases.
- Helps in identifying generator functions that are possibly incomplete or mistakenly marked as generators, thus maintaining code quality.
- Aids in enforcing best practices and consistent usage of generator functions, making the code easier to understand and maintain by fellow developers.
Enforce spacing between rest and spread operators and their expressions
const badSpread = {...obj};
function badFunction(...args){
console.log(args);
}
- The rule helps maintain consistency in the codebase regarding the use of spaces around rest and spread operators, which can improve readability and reduce the cognitive load on developers trying to understand the intent of the code.
- By enforcing a specific style (either always having a space or never having it) between rest and spread operators and their expressions, this rule can prevent potential syntax or parsing errors that might occur in certain JavaScript engines or when minifying code.
- It assists in code reviews by automatically flagging stylistic issues related to spacing around rest and spread operators, thus allowing reviewers to focus on more critical aspects of the code such as logic errors, architectural decisions, and code smells.
- The rule includes a fixer function that can automatically correct the spacing around rest and spread operators to comply with the configured option (“always” or “never”), thus saving developers time during refactoring or initial development.
Enforce consistent spacing before and after semicolons
let a = 1;let b = 2;
for(let i = 0;i < 5;i++){ console.log(i);}
- This ESLint rule enforces consistency in the spacing before and after semicolons, which can help in maintaining a uniform code style across the project. Uniform code style makes the code more readable and easier to understand for new or existing team members.
- By specifically focusing on the spacing around semicolons, it avoids the introduction of subtle syntax errors that might occur if semicolons are either closely packed with other tokens or if unnecessary spaces are introduced inadvertently.
- The rule’s flexibility to configure
requireSpaceBefore
andrequireSpaceAfter
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. - It automatically fixes spacing inconsistencies, reducing the manual effort required during code reviews and allowing developers to focus on more critical aspects of the code. Automatic fixes help in quickly conforming to the coding standards without disrupting the development flow.
Enforce location of semicolons
const name = "John"
; const age = 30
; const city = "New York"
-
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.
Require or disallow semicolons instead of ASI
const myFunction = () => {
console.log("Hello, world")
}
- This rule specifically targets the inclusion or exclusion of semicolons to enforce a consistent coding style, reducing the risk of syntax errors or potential automatic semicolon insertion (ASI) pitfalls, especially in complex codebases.
- By providing options for exceptions, such as omitting semicolons in single-line blocks or class bodies, it allows teams to tailor the rule to their preferences while maintaining readability and reducing visual clutter in concise constructions.
- The rule includes mechanisms to detect potential hazards where omitting a semicolon could lead to code being interpreted in an unintended way, such as when a line starts with a character that could make the previous statement behave differently, providing a safeguard against common ASI-related bugs.
- It is designed to work well with other rules and the overall ESLint ecosystem by including logic to avoid conflicts, like expanding the range of semicolon removal to retain surrounding tokens, ensuring that automatic fixes do not introduce new errors or conflict with other linting rules.
Enforce sorted import declarations within modules
import b from 'foo.js';
import a from 'bar.js';
import * as Baz from 'baz.js';
-
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.
Require object keys to be sorted
const userProfile = {
username: 'johndoe',
age: 30,
surname: 'Doe',
firstName: 'John'
};
- This ESLint rule, “sort-keys,” enforces a consistent ordering of object keys, which can significantly improve readability and maintainability by making it easier to locate and verify if a particular property exists in an object, especially in large objects or when working with multiple developers on the same codebase.
- The rule offers various configuration options, including the ability to sort keys in ascending or descending order, case sensitivity, and natural sorting. This flexibility allows teams to customize the rule according to their specific coding standards and preferences, ensuring consistency across the project.
- By supporting the option to allow line-separated groups within objects, the rule can accommodate different logical groupings of properties while still enforcing sorting within those groups. This feature enables developers to organize properties in a way that makes sense semantically without compromising on the overall sorting requirement.
- The rule’s capability to enforce sorting only when the number of keys exceeds a configurable minimum threshold (“minKeys”) provides a balance between strict enforcement and practical convenience. For smaller objects where sorting might be less critical or obvious, this option helps avoid unnecessary linting noise, allowing developers to focus on more impactful issues.
Require variables within the same declaration block to be sorted
let b = 2, a = 1, d = 4, c = 3;
- Ensures consistency and readability within the codebase by enforcing a uniform order of variable declarations, making it easier to locate and evaluate variables at a glance.
- Helps in reducing merge conflicts in version control systems, as variables ordered in a consistent manner are less likely to be edited in conflicting ways across different branches.
- Facilitates code review processes by establishing a predictable structure for variable declarations, allowing reviewers to quickly assess the presence and correct declaration of required variables.
- Aids in identifying duplicate variable declarations within the same block, as sorting can put potential duplicates next to each other, making them more noticeable during manual code inspection or automated linting processes.
Enforce consistent spacing before blocks
if(condition){
// code to execute
}
function test(){
// function body
}
class MyClass{
constructor(){
// constructor body
}
}
-
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.
Enforce consistent spacing before function
definition opening parenthesis
function example() {
console.log('Hello world!');
}
const anotherExample =function() {
console.log('Another example!');
}
const arrowFunction =()=> {
console.log('Arrow function example!');
}
-
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.
Enforce consistent spacing inside parentheses
function example( param1,param2 ) {
console.log( param1,param2);
}
if ( example( "Test1","Test2" ) ) {
console.log("Spacing is inconsistent" );
}
-
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.
Require spacing around infix operators
let a=2;
let b=3;
let sum=a+b;
- Enforces readability and consistency across the codebase by requiring spaces around operators such as
=
,+
,?
,:
, which can significantly enhance the legibility of complex expressions and assignments by visually separating operands from their operators. - Helps in maintaining a uniform coding style that adheres to common JavaScript best practices, making it easier for teams to understand each other’s code, facilitating more efficient code reviews and collaboration.
- The rule has provisions for automatic fixing, which streamlines the formatting process by correcting spacing issues without developer intervention, saving time and reducing the likelihood of manual errors during code formatting.
- By offering an option to consider
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.
Enforce consistent spacing before or after unary operators
// Bad: No space after unary operator "!"
let isActive = !condition;
// Bad: No space before unary operator "++"
count++;
// Bad: No space after unary word operator "delete"
delete obj.property;
// Bad: No space after unary word operator "typeof"
let type = typeof value;
-
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
anddelete
) 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.
Enforce consistent spacing after the //
or /*
in a comment
// This is a bad example for single line comment
function badExample1() {
return;
}
/*This is a bad example for block comment*/
function badExample2() {
return;
}
//An example with no space after slashes
function badExample3() {
return;
}
-
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.
Require or disallow strict mode directives
function logMessage() {
'use strict';
console.log("This function unnecessarily uses strict mode.");
}
- The rule assists in maintaining consistency regarding the use of strict mode directives across different scopes and modules in JavaScript code, which can help avoid potential issues or unexpected behavior due to inconsistent strict mode usage.
- It automatically identifies and can fix places where
'use strict';
is unnecessary, such as in classes and modules where strict mode is implied, helping to clean up the codebase and improve readability. - By providing configurations like “safe”, “global”, “function”, and “implied”, it offers flexibility in enforcing strict mode, allowing teams to align the rule with their specific coding standards or the particularities of their project structure.
- The rule’s capability to report and automatically fix multiple or misplaced
'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.
Enforce spacing around colons of switch statements
switch(expression) {
case 1: // Notice there's no space before the colon
doSomething();
break;
case 2 :// Notice there's an unnecessary space before the colon and missing after
doSomethingElse();
break;
}
- Enforces a consistent spacing style around colons in switch cases, which aids in maintaining code readability and standardization across a project. Specifically, it ensures that there is a uniform approach to spacing around the colons, making it easier to read and understand the boundaries of case statements.
- Provides automatic fix capabilities, which can help developers quickly correct spacing issues around colons in switch cases without manually adjusting them. This feature serves to streamline the process of adhering to coding standards and reduces the time spent on formatting concerns.
- Allows for customizable spacing options before and after the colon in switch cases, catering to different coding style preferences. This flexibility ensures that teams can enforce their own spacing standards, whether they prefer spaces before, after, or both sides of the colon, promoting a tailored and consistent coding style within the team.
- Helps in avoiding syntax errors or misunderstandings that could arise from inconsistent spacing, especially for newcomers to the codebase who may rely on clear visual cues to comprehend the code structure. This rule aids in minimizing potential confusion by ensuring that the visual structure of switch cases is consistently applied throughout the codebase.
Require symbol descriptions
const uniqueKey = Symbol();
- Ensures that each
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. - Enhances code readability by requiring developers to provide a meaningful description when creating symbols. This practice encourages developers to think about the purpose of the symbol and communicate that purpose through code, making it easier for others (and their future selves) to understand the code’s intention.
- Helps in maintaining a consistent codebase, especially in large projects where symbols are used extensively. By enforcing the inclusion of descriptions, this rule helps prevent the misuse or confusion of symbols across different parts of the application.
- Reduces the risk of errors or bugs related to the misuse of symbols, as the descriptive strings can act as a form of documentation within the code. When symbols are used with descriptions, it is easier to ensure that they are applied correctly in their respective contexts, which can prevent potential issues in application logic.
Require or disallow spacing around embedded expressions of template strings
const name = "world";
console.log(`Hello,${name}!`);
- This rule enforces a consistent and readable formatting style in template literals by requiring or disallowing spaces around embedded expressions. This makes the code easier to read and understand for developers, particularly in complex template strings where expressions are embedded.
- It helps avoid confusion and potential errors by clearly distinguishing between the template literal’s static parts and the embedded expressions. Without proper spacing, it’s easier to misinterpret the boundaries of an expression within the template.
- The rule’s auto-fixing capability ensures that developers don’t have to manually correct spacing issues around embedded expressions. This saves time during development and code review processes and helps maintain a consistent code style across the project without requiring manual intervention.
- By providing options to enforce either always having space or never having space around embedded expressions, this rule can be aligned with specific project or team style guidelines, ensuring consistency across different codebases under the same development standards. This flexibility allows teams to adhere to their preferred coding standards while still enforcing a rule that improves readability and maintainability.
Require or disallow spacing between template tags and their literals
// This code snippet violates the `template-tag-spacing` ESLint rule
// by having a space between the template tag and the template literal.
const tagFunction = (strings, expression) => {
return strings[0] + expression.toUpperCase();
};
const value = 'world';
console.log(tagFunction `Hello, ${value}!`);
- Enforces consistency in the spacing between template tags and their literals, making the code easier to read and maintain. By either requiring or disallowing space based on the configuration, it ensures all developers on a project follow a common style.
- Helps avoid syntactic ambiguities in code where spaces might lead to misinterpretation of a template literal as a separate expression, especially in complex codebases.
- Automates the correction of spacing issues between template tags and literals, saving developers time during code reviews and reducing manual linting efforts. The rule’s
fix
function can automatically adjust spacing to meet the rule’s requirements without developer intervention. - Increases code clarity by ensuring that template literals are immediately recognizable and distinct from adjacent code elements. This can be particularly beneficial for developers new to JavaScript or transitioning from other programming languages, aiding in quicker comprehension of template literal syntax.
Require or disallow Unicode byte order mark (BOM)
// Assuming this file starts with a BOM
function greet() {
console.log('Hello, world!');
}
greet();
-
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.
Require calls to isNaN()
when checking for NaN
// Direct comparison with NaN in a conditional
if (value === NaN) {
console.log("This will never be true!");
}
// Using `NaN` in a switch case, which is ineffective
switch (value) {
case NaN:
console.log("This case will never be executed!");
break;
default:
console.log("Always ends up here.");
}
// Using `NaN` with `indexOf` or `lastIndexOf`, which is incorrect
const array = [1, 2, 3];
if (array.indexOf(NaN) > -1) {
console.log("This logic is flawed.");
}
-
This rule specifically addresses the common misconception in JavaScript that
NaN
can be directly compared using equality or inequality operators. SinceNaN
is the only value in JavaScript that is not equal to itself, direct comparisons likevalue === NaN
will always return false, leading to bugs in the code. By enforcing the usage ofisNaN()
, it ensures that checks forNaN
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 toNaN
. However, this will never work as intended because of how JavaScript treatsNaN
. This rule helps avoid such ineffective code by flagging directNaN
usage in switch cases and suggesting alternatives that correctly determine if the value isNaN
. -
When using methods like
.indexOf()
or.lastIndexOf()
, developers might expect these methods to findNaN
in an array. However, due to the same equality comparison issue, these methods will not work as intended when directly passedNaN
as a parameter. This rule highlights these incorrect usages, directing developers towards more suitable methods for checking the presence ofNaN
in arrays, such as using theisNaN()
function within a filtering method likearray.some()
. -
By enforcing checks for
NaN
to use theisNaN()
function, this rule promotes clearer intent and more reliable code. Direct comparisons and method usages that don’t work withNaN
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 ofNaN
.
Enforce valid JSDoc comments
/**
* Adds two numbers.
* @param num1 The first number.
* @param num2 The second number.
*/
function add(num1, num2) {
return num1 + num2;
}
- This rule enforces developers to explicitly document the types of parameters and return values in JSDoc comments, which can significantly improve code readability and maintainability by clearly specifying what data types are expected. This is particularly helpful in dynamically typed languages like JavaScript, where data types are not explicitly declared in the function signature.
- By requiring a description for both parameters and return values, it ensures that developers provide meaningful documentation on the purpose and usage of functions, which facilitates better understanding and usage of the codebase by others, including newcomers or when revisiting code after a long time.
- The rule’s ability to enforce specific tag preferences (e.g., preferring
@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. - It promotes best practices by ensuring that functions without a return value or with a return value that is implicitly
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.
Enforce comparing typeof
expressions against valid strings
if (typeof myVariable == 'undefinded') { // Notice the typo in 'undefined'
console.log('Variable is undefined');
}
- The rule prevents common typos in string literals that represent typeof return values, such as ‘undefinded’ instead of ‘undefined’, by enforcing comparisons against a set of valid strings. This directly addresses a frequent source of bugs, especially for those not deeply familiar with the specific return values of the typeof operator.
- By requiring comparisons to be against valid typeof return values, the rule encourages developers to understand and correctly use the typeof operator, fostering better type checking and validation in JavaScript projects. This is particularly useful for projects without static typing aids like TypeScript.
- The rule’s option to enforce the use of string literals in typeof comparisons (if enabled) ensures that the comparisons are against predictable, hardcoded strings rather than variables whose values might not be valid typeof return values. This reduces the risk of runtime errors due to dynamic or incorrect values being compared against the result of typeof.
- It accounts for global variables by not enforcing the rule if the identifier refers to an undeclared global variable. This flexibility allows for the rule to be effective in a variety of coding environments, including those where external scripts define global variables, without producing unnecessary warnings or errors that would detract from its utility.
Require var
declarations be placed at the top of their containing scope
function badFunction() {
console.log("Doing something before declaring variables...");
var firstVar = "First";
console.log(firstVar);
// Some other code
for (var i = 0; i < 5; i++) {
console.log("Looping through: ", i);
}
var secondVar = "Second";
console.log(secondVar);
}
-
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.
Require parentheses around immediate function
invocations
var x = function () { return { y: 1 }; }();
-
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
andapply
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.
Require parenthesis around regex literals
const regexTest = /abc/.test("abcabc");
-
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.
Require or disallow spacing around the *
in yield*
expressions
function* anotherGenerator(i) {
yield*i; // The spacing around '*' does not follow the preferred style
}
function* generator(i) {
yield*anotherGenerator(i); // The spacing around '*' is also incorrect based on the setting
}
- Ensures consistency in coding style specifically for
yield*
expressions, which enhances code readability and maintainability by having a uniform appearance. - Helps prevent syntax or runtime errors that might arise from incorrect spacing around the
*
inyield*
expressions, by enforcing a standard spacing convention. - Can automatically fix spacing issues around the
*
inyield*
expressions, saving developers time and effort in manually correcting these to adhere to the preferred style. - Supports customizable configurations (
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.
Require or disallow “Yoda” conditions
function checkAccess(age) {
// This is a Yoda condition, which should be avoided based on the rule's configuration
if (18 <= age && age < 65) {
return true;
}
return false;
}
-
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.