Get Started
- CodeAnt AI
- Control Center
- Pull Request Review
- IDE
- Compliance
- Anti-Patterns
- Code Governance
- Infrastructure Security Database
- Application Security Database
Unicorn
Improve regexes by making them shorter, consistent, and safer.
const regex = /[a-zA-Z0-9_-]+/;
- This ESLint rule enhances the readability of regex patterns by transforming them into shorter versions without altering their functionality. For example, it would convert
[a-zA-Z0-9_-]+
into\w+
, which is substantially easier to understand at a glance. - It ensures consistency in the project’s regex expressions by standardizing patterns where possible. Consistent use of regex patterns can help in maintaining the code, as it reduces the cognitive load on developers who work with or review the code.
- By including a mechanism to avoid optimizing regexes with certain flags (specifically ‘u’ and ‘v’ flags, which are known to have issues), the rule prevents potential compatibility issues or bugs that could arise from the transformation. This cautious approach respects the intricacies of regex behavior across different contexts and ensures reliable operation.
- The rule also offers an automated fix (where applicable) for identified suboptimal regex patterns, thereby reducing the manual effort required for such optimizations and promoting a more efficient and error-free codebase. This can be particularly beneficial in large projects where manual tracking and updating of all regex patterns would be impractical.
Enforce a specific parameter name in catch clauses.
try {
// Some operation that might fail
} catch (err) {
console.error(err);
}
- The rule enforces a consistent naming convention for error parameters in catch clauses, which helps in maintaining consistency across the codebase. This consistency aids in readability and makes the code easier to understand for new developers or when revisiting old code.
- It provides a flexible configuration through the
options
object, allowing developers to specify the expected error parameter name, plus an array of names (or patterns) to ignore. This flexibility ensures that the rule can be adapted to fit the project’s naming conventions without forcing a one-size-fits-all approach. - The rule accommodates variations in naming by allowing names that end with the expected name or the expected name with its first character capitalized. This feature supports common practices like appending additional context to error names (e.g.,
networkError
) while still enforcing the base naming convention. - It includes logic to handle edge cases and avoid potential conflicts, such as avoiding variable name capture and safely ignoring catch parameters that are not used within their block (indicated by the name
_
and zero references). This careful consideration prevents the rule from applying fixes that could introduce bugs or affect the functionality of the code.
Use destructured variables over properties.
const user = {
name: 'John Doe',
age: 30,
location: 'New York'
};
console.log(user.name);
console.log(user.age);
-
Encourages cleaner, more readable code by promoting the use of destructuring, which reduces redundancy when accessing multiple properties from the same object. This makes the codebase more maintainable and understandable, especially for new developers or when revisiting old code.
-
Helps to avoid repeated access to the same object property within a scope, which can lead to less efficient code. By encouraging destructuring at the beginning of a scope, it minimizes object property access times and potentially improves performance in cases where property access is costly.
-
Reduces typo-related bugs by minimizing the number of times a developer needs to manually type the path to a property within an object. When using destructuring, property names are specified once and reused, thus reducing the potential for errors in typing long property paths multiple times.
-
Supports cleaner integration with modern JavaScript features, like the rest operator (…), by setting a structured precedent for object property access within the codebase. By promoting destructuring syntax, it aligns the code with ES6+ best practices, ensuring that developers are familiar with current language features and making the code more future-proof.
Move function definitions to the highest possible scope.
const filterEvenNumbers = (numbers) => {
const isEven = (number) => number % 2 === 0;
return numbers.filter(isEven);
};
filterEvenNumbers([1, 2, 3, 4, 5]);
- Encourages better code structuring by advocating for the relocation of function definitions to the highest applicable scope, which aligns with the principle of least privilege, ensuring functions are only available where they are strictly needed. This prevents potential misuse in larger codebases.
- Enhances code readability and maintainability by reducing clutter within functions, making the primary logic of each function more apparent at first glance. By moving helper functions to an outer scope, the core functionality of each function becomes clearer.
- Improves performance in some scenarios by avoiding the redefinition of functions within other functions during runtime. For instance, in the provided example,
isEven
is moved outside offilterEvenNumbers
, ensuring it is created once, rather than being recreated every timefilterEvenNumbers
is called. - Facilitates code reuse by positioning functions in a scope where they can be more easily shared across multiple other functions or components, thus adhering to the DRY (Don’t Repeat Yourself) principle. In the provided example,
isEven
could potentially be used by other functions besidesfilterEvenNumbers
.
Enforce correct Error
subclassing.
class CustomError extends Error {
constructor(m) {
super(); // Not passing the message to the base Error constructor
this.name = 'CustomError';
}
}
throw new CustomError('Something happened');
-
It ensures that custom errors correctly pass messages to the base
Error
constructor, allowing for more informative error messages and easier debugging. This is crucial because if the message is not passed to the baseError
constructor (as shown in the ‘bad’ example), it leads to a loss of the error message, making it harder to understand the context of the error. -
By enforcing the setting of the prototype explicitly using
Object.setPrototypeOf(this, CustomError.prototype);
, it supports a proper inheritance chain. This is particularly important in environments that may not handle subclassing of built-in objects likeError
correctly, ensuring that instanceof checks and other prototype-based behaviors work as expected. -
The rule focuses on preventing common pitfalls in defining custom errors, such as forgetting to pass arguments to the superclass or incorrect handling of prototypes. These mistakes can lead to errors that are harder to trace and may behave inconsistently across different JavaScript environments.
-
It promotes a standardized way of defining custom errors, leading to code uniformity and easier maintenance. By following the pattern enforced by the rule (illustrated in the ‘fix’ example), developers can ensure that all custom errors across a project or an organization are defined using a consistent structure, improving readability and reducing the chances of bugs related to error handling.
Enforce no spaces between braces.
// Object with spaces between braces
const myObject = { };
// Array with spaces between braces (though the primary focus would likely be on objects for this rule)
const myArray = [ ];
-
This rule specifically targets a common coding style preference by enforcing no spaces between braces, which aids in maintaining consistency across the codebase, especially in projects where multiple developers are involved. Consistency here means that all empty objects and similar structures follow the same formatting convention, avoiding stylistic disagreements or the need for manual corrections during code reviews.
-
By automatically enforcing this stylistic choice, it helps save time during both the writing and reviewing of code. Developers no longer need to manually check and correct these spaces in pull requests or commits, streamlining the development process and focusing efforts on more critical issues like functionality and logic errors.
-
The rule potentially prevents minor errors or confusion in distinguishing between different kinds of empty structures in the code. For instance, it makes it visually clearer that an object or array is indeed intended to be empty and is not a typographical error or a place where content was mistakenly omitted, enhancing code readability and intent communication.
-
It also makes automated code formatting tools more effective by providing them a clear rule to follow regarding brace spacing. This compatibility with tooling ensures that even if a developer forgets to format their code correctly or introduces spaces by habit, the tools can automatically correct these to adhere to the project’s coding standards without manual intervention.
Enforce passing a message
value when creating a built-in error.
// Example without any message
throw new Error();
// Example with an incorrect type as message
throw new TypeError({ errorMessage: "This should be a string" });
- Enforces clarity in error reporting by requiring a textual message argument when creating built-in error objects, which aids in debugging and understanding the code’s execution flow.
- Helps maintain consistency in error handling across the codebase by standardizing how errors are constructed, making code easier to read and maintain.
- Catches common mistakes such as passing objects or arrays as the error message, which are not as informative or readable as string messages, thereby improving the quality of error reporting.
- Aids in the identification and correction of potentially empty or undefined error messages, preventing cryptic or unhelpful errors from being thrown, and thereby enhancing error diagnostics.
Require escape sequences to use uppercase values.
const message = 'Press \x1b[31mEnter\x1b[0m to continue...';
const regexPattern = /\x1a\[\d+m/;
const templateString = `Error: \x1b[31mFile not found\x1b[0m.`;
-
The rule enforces a consistent casing for escape sequences within string literals, regex literals, and template strings, specifically requiring uppercase hex values. This consistency can aid in readability and maintainability of the code, as developers will encounter a standardized format when dealing with escape sequences across the codebase.
-
By requiring uppercase values, the rule may help in distinguishing escape sequences from regular text more easily, as the contrast between the escape sequence’s uppercase notation and possible lowercase textual content could enhance clarity, especially in complex strings or regular expressions.
-
The rule indirectly encourages developers to gain a deeper understanding of escape sequences and their usage within JavaScript by setting a convention for their casing. This educational aspect can lead to better coding practices and awareness regarding how data is represented and manipulated in strings and regular expressions.
-
It facilitates automated code formatting and linting tools to enforce a particular coding style regarding escape sequences, which can reduce the time spent on code reviews and manual corrections related to stylistic inconsistencies. Consequently, this allows developers to focus more on the logic and performance aspects of the code rather than formatting issues.
Add expiration conditions to TODO comments.
// A TODO without expiration
// TODO: Refactor this function to improve performance
function performCalculation() {
// complex logic
}
// Another improperly formatted TODO
// FIXME remove this unnecessary variable
let unnecessary = true;
- The rule enforces adding expiration conditions to TODO comments, making developers more accountable for resolving TODOs within a specified timeframe. This prevents accumulation of outdated or irrelevant TODOs in the codebase.
- By allowing the specification of terms like ‘todo’, ‘fixme’, and ‘xxx’, the rule can be tailored to the project’s conventions for marking unfinished code. This flexibility ensures comprehensive coverage of all the placeholders for future work.
- The rule’s capability to ignore comments based on regex patterns or to conditionally ignore expiration dates on pull requests provides the flexibility to adapt the rule to various development workflows, ensuring that the rule can be effectively applied without disrupting established practices.
- With support for evaluating conditions such as package versions, dependencies, and engines, the rule extends beyond just date-based expirations, enabling developers to create more dynamic and context-aware TODO comments. This feature encourages developers to specify more detailed and actionable conditions for revisiting the TODOs, improving the code maintenance process.
Enforce explicitly comparing the length
or size
property of a value.
const fruits = ['apple', 'banana', 'cherry'];
if (fruits.length) {
console.log('We have some fruits!');
}
-
Prevents ambiguity in conditionals by requiring an explicit comparison of the
length
orsize
which clarifies the intention of checking for a non-empty array or collection, rather than inadvertently relying on truthy or falsy values. -
Increases code readability and maintainability by enforcing a uniform approach to length or size checks, making it easier for developers to understand the code’s purpose at a glance without having to interpret the implications of the presence or absence of a direct comparison.
-
Helps avoid logical errors in cases where the
length
property might not be a simple number, for example, when it is overridden or manipulated, ensuring that the condition evaluates as expected by explicitly comparing it to a specific value. -
Facilitates easier code reviews and decreases the likelihood of bugs slipping through, since the explicit comparison makes the code’s behavior more predictable and less prone to misinterpretation by developers unfamiliar with JavaScript’s truthy and falsy value conventions.
Enforce a case style for filenames.
// The content of the file isn't relevant for this rule.
// Filename: myFileName.js
console.log('This is an improperly named file.');
-
It promotes consistency in filename conventions across a project, making it easier to understand the file structure and navigate the project. By enforcing a specific case style, developers can quickly identify files and understand the naming conventions used within the project without having to guess or learn multiple patterns.
-
The rule helps prevent potential bugs related to case sensitivity in file names, especially when moving between operating systems that treat filename case differently, such as Windows (case-insensitive) compared to Linux and macOS (case-sensitive). This ensures that the codebase is more portable across different environments.
-
By allowing configuration options, including the ability to ignore certain files via regular expressions, the rule provides flexibility to accommodate special cases or existing naming schemes within parts of the project. This ensures that teams can adopt the rule without having to rename every file immediately or violate the rule where exceptions are necessary.
-
The rule can automatically suggest or fix filenames to match the desired case convention, reducing the manual effort required by developers to comply with the project’s naming standards. This feature enhances developer productivity and ensures that naming convention errors are corrected immediately, leading to a cleaner and more maintainable code base.