Get Started
- CodeAnt AI
- Control Center
- Pull Request Review
- IDE
- Compliance
- Anti-Patterns
- Code Governance
- Infrastructure Security Database
- Application Security Database
Autofix
Disallow the use of alert
, confirm
, and prompt
function showWarning() {
alert("Warning! You are about to delete your account.");
}
- Enforcing this rule ensures that applications do not use
alert
,confirm
, andprompt
methods that are considered disruptive for the user experience. These methods halt webpage execution and do not provide customization options, leading to a poor user interface. - This rule guides developers towards more modern and user-friendly alternatives like custom modal dialogs, which can be styled and scripted to integrate seamlessly with the application’s design and behavior, enhancing the overall user interaction.
- By disallowing these methods, the rule helps in maintaining a consistent approach across the development team to handle user interactions and feedback without resorting to default browser dialogs, thereby ensuring a uniform look and feel across different parts of the application.
- Application security is indirectly improved by following this rule. The use of custom methods for user confirmation or input sanitation can be more easily controlled and audited, compared to the native browser methods which are harder to manage and could potentially be exploited in phishing attacks or to deceive users.
Disallow the use of arguments.caller
or arguments.callee
var factorial = function(n) {
if (n <= 1) {
return 1;
} else {
return n * arguments.callee(n - 1);
}
}
-
This ESLint rule targets the prevention of using
arguments.caller
andarguments.callee
, which are both deprecated in ES5 strict mode and considered bad practice in modern JavaScript development. Their use can lead to optimization issues and make code difficult to manage, especially in strict mode where their use will throw an error. -
By disallowing
arguments.caller
andarguments.callee
, the rule encourages the use of named functions or other modern alternatives, which can lead to more readable and maintainable code. For example, converting a recursive anonymous function to a named function improves stack traces in error messages and makes the code more understandable. -
The rule can potentially help in future-proofing the codebase for migration to newer JavaScript versions or strict mode, as reliance on deprecated features can complicate such transitions. Preventing these features ensures that code adheres to best practices and does not rely on behavior that might be removed or unsupported in future JavaScript engines or environments.
-
Implementing this rule within a development process helps establish a consistent coding standard that avoids deprecated and potentially problematic JavaScript features. As a result, it can contribute to overall code quality, reduce the likelihood of bugs related to scope and binding, and ease maintenance and debugging efforts by using clearer and more predictable constructs.
Disallow the use of console
function debugData(data) {
console.log(data); // This is what the ESLint rule aims to prevent.
}
- Encourages developers to use more sophisticated logging frameworks for better control over logging behavior and output, suitable for development, testing, and production environments, rather than relying on the basic
console.log
method. - Helps maintain a cleaner console output, which is especially important in a production environment where excessive logging can lead to performance issues and make it difficult to spot real issues among the noise.
- Prevents potential leakage of sensitive information through console logs that are inadvertently left in the codebase, enhancing the application’s security posture.
- Facilitates code consistency and adherence to best practices within a team or organization by automatically flagging uses of
console
methods, ensuring that alternatives like centralized logging solutions are considered and implemented.
Disallow the use of debugger
function someFunction() {
debugger;
console.log('Debugging some issue');
}
-
The rule is specifically designed to disallow the use of the
debugger
statement in JavaScript code. This is beneficial because leavingdebugger
statements in production code can inadvertently halt the execution of JavaScript in browsers that have developer tools open, leading to a poor user experience. -
It includes autofix functionality, which means when the rule is violated, it can automatically comment out or remove the
debugger
statement, thus enforcing best practices without requiring manual intervention by the developer. This automation helps in maintaining code quality and saving time during development and code review processes. -
The rule’s logic considers the context, including file names, source code, settings, and options. This means that it is not just a simple text replacement but a contextual analysis to ensure that the autofix does not inadvertently change the code’s behavior beyond removing or commenting out the debugger statements. This context-aware approach increases the safety and reliability of the autofix feature.
-
By focusing on disallowing
debugger
statements, this rule helps enforce a coding standard across the development team that prioritizes the use of other debugging methods, such as logging to the console or using modern development tools and breakpoints. This standardization helps in creating a consistent debugging approach within a project, making the code more maintainable and understandable for all team members.
Disallow null
comparisons without type-checking operators
if (userInput == null) {
console.log("The userInput variable is either null or undefined.");
}
-
This rule helps ensure strict comparison (
===
) withnull
, making sure the check distinguishes betweennull
andundefined
values explicitly. In JavaScript,==
null matches bothnull
andundefined
, which can lead to unintended consequences if the distinction matters in the code logic. -
By enforcing the use of strict equality operators with
null
, the rule aids in promoting coding best practices that improve the predictability and readability of the code. This can be particularly useful in codebases wherenull
andundefined
are used with specific and distinct meanings. -
The rule can prevent potential bugs that might arise from using loose equality checks (
== null
), which could inadvertently pass bothnull
andundefined
values. This is especially important in situations where only one of these values (null
orundefined
) is considered valid, or they trigger different behaviors. -
It supports the automatic correction of code that doesn’t adhere to the rule, thus reducing manual intervention and helping maintain consistency across the codebase. This automated fix feature can save developers time and effort during the development and code review processes, ensuring that subtle bugs related to null comparison are caught early and corrected.
Disallow new
operators with the Symbol
object
const uniqueId = new Symbol("myUniqueID");
- Enforcing the use of
Symbol
correctly without thenew
keyword prevents runtime errors, becauseSymbol
is not a constructor. The ES6Symbol
object should be instantiated withoutnew
. Usingnew
withSymbol
will throw a TypeError, so this rule helps to catch such errors during the linting phase instead of at runtime. - By disallowing
new
operators with theSymbol
object, the rule promotes the use of ES6 features according to their specification. This adherence not only ensures code correctness but also enhances readability and maintains consistency across codebases that utilize modern JavaScript features. - This specific linting rule aids developers who might be transitioning from other languages or earlier JavaScript versions, where the use of
new
for creating instances is more common. It serves as an educational tool that guides them towards the correct usage ofSymbol
, aligning their coding practices with standard JavaScript idioms. - By automatically fixing instances where
new Symbol()
is incorrectly used, this rule not only flags potential code issues but also offers a quick resolution path. This reduces the manual effort required to correct such mistakes and accelerates the development process, ensuring more efficient code refactoring and maintenance.
Disallow the unary operators ++
and --
let count = 0;
for(let i = 0; i < 10; i++) {
count++;
}
console.log(count);
- This ESLint rule ensures code consistency by disallowing the unary operators
++
and--
, which encourages the use of+= 1
or-= 1
instead. This approach can make the code clearer, especially for those not familiar with the unary operators or coming from languages where these operators are not used or behave differently. - By enforcing this rule, it can potentially prevent auto-increment or auto-decrement related side effects or bugs in complex expressions or when used in combination with other operators, since the explicit
+= 1
or-= 1
is less prone to misinterpretation or misuse. - This rule supports the intention of making the code more accessible and easier to understand for beginners or non-native JavaScript developers. The
++
and--
operators might be overlooked or misunderstood, whereas+= 1
and-= 1
explicitly state the operation’s intent. - The rule indirectly promotes the principle of immutable data patterns. In functional programming styles where data immutability is preferred, avoiding
++
and--
in favor of+= 1
and-= 1
can align better with patterns that avoid modifying data in place. This can lead to code that’s easier to reason about in terms of data flow and state changes.
Disallow the use of the __proto__
property
const animal = {
isAlive: true
};
const dog = {
barks: true
};
dog.__proto__ = animal;
console.log(dog.isAlive); // true - because dog now inherits from animal
-
This rule specifically targets the prohibition of the
__proto__
property, which is a deprecated and non-standard feature for setting an object’s prototype. Using__proto__
can lead to compatibility and security issues in JavaScript code, making the enforcement of this rule crucial for maintaining code quality and ensuring cross-browser compatibility. -
The rule promotes the use of
Object.create
as a recommended approach for prototype chaining. This method is part of the ECMAScript standard and provides a clearer and more secure way to set up prototype chains, allowing for the definition of additional properties at the time of object creation. This practice leads to code that is both safer and more aligned with modern JavaScript development standards. -
Enforcing this rule helps prevent prototype pollution vulnerabilities. Since the
__proto__
property can be accessed and modified through user input in some cases, blocking its usage reduces the surface area for attackers aiming to manipulate an application’s object prototype, leading to potentially severe security risks. -
It encourages developers to think more deeply about their application’s structure and the relationships between objects. By requiring the use of
Object.create
and the explicit definition of properties, developers are nudged towards a more thoughtful design, potentially improving code readability and maintainability by explicitly defining inheritance and property characteristics.
Disallow calling some Object.prototype
methods directly on objects
var obj = {
prop: 'exists'
};
// BAD: Directly using hasOwnProperty
if (obj.hasOwnProperty('prop')) {
console.log('Property exists.');
}
- Prevents potential shadowing issues where object properties might be named the same as
Object.prototype
methods, leading to unexpected bugs when methods likehasOwnProperty
are called directly on objects. - Encourages the use of safer, more robust methods of checking object properties by borrowing
Object.prototype
methods and using them withcall
orapply
, thereby ensuring that the check is always performed against the object’s properties, not its methods. - Enhances code maintainability and readability by promoting a pattern of accessing potentially overridden methods in a way that is clear and consistent, making it easier for developers to reason about and review code.
- Helps in preventing security vulnerabilities that might arise from calling
Object.prototype
methods directly on user-supplied objects, which could be manipulated to cause unexpected behavior or denial-of-service attacks by creating objects with properties likehasOwnProperty
.
Disallow throwing literals as exceptions
function checkUser(user) {
if (!user) {
throw "No user found"; // This line violates the rule by throwing a string instead of an error object.
}
}
- Enforces the use of Error objects when throwing exceptions, which improves the debugging experience by providing a stack trace. Throwing a plain string or literal does not offer a stack trace, making it harder to trace the source of the error.
- Promotes consistency in error handling across the codebase. By requiring Error objects for throwing exceptions, developers follow a unified approach which enhances code readability and maintainability.
- Facilitates richer error information since Error objects can include additional properties such as
name
andmessage
, and allow for further customization. This is in contrast to literals, which are limited in the scope of information they convey. - Aids in catching errors programmatically. When literals are thrown, it’s more challenging to distinguish between different types of errors. Using Error objects allows for more precise error handling, such as using
try/catch
blocks to catch specific types of errors based on their properties.
Disallow unused variables
function processData() {
const data = fetchSomeData();
const unusedVariable = 'This is not used anywhere';
console.log(data);
}
-
This ESLint rule specifically targets and identifies unused variables within the code, which directly contributes to cleaner code by removing clutter that is not being utilized. As a result, the overall readability and maintainability of the code improve. In large projects, especially, this can significantly reduce the cognitive load on developers trying to understand the flow and purpose of different code segments.
-
By disallowing unused variables, it indirectly encourages developers to think more critically about their code. Developers are prompted to consider whether each piece of their code has a purpose, which can lead to more efficient programming patterns and practices. Over time, this could contribute to a culture of writing more concise and purposeful code within a team or project.
-
The rule’s implementation includes context attributes like
filename
,sourceCode
,settings
, andoptions
, which allows for a more tailored and contextual analysis of the code. This specificity enables the rule to be adaptable to different environments and project settings, ensuring that it can be effectively applied across a wide range of projects with varying configurations. -
The autofix capability that is implied by the rule’s naming convention (
autofix/no-unused-vars
) suggests that not only does the rule identify unused variables, but it also potentially offers a fix to automatically remove such variables. This automation can save developers time and effort in manual code clean-up, accelerating the development process while simultaneously enforcing code quality standards. This is particularly advantageous in large codebases where manually identifying and removing unused variables can be tedious and prone to human error.
Disallow unnecessary catch
clauses
async function fetchData() {
try {
const response = await fetch('https://example.com/data');
const data = await response.json();
return data;
} catch (error) {
throw error; // This catch clause is unnecessary.
}
}
-
This rule helps in identifying redundant
catch
clauses that merely rethrow the caught error without handling it, leading to cleaner and more readable code. As seen in the example, the catch block doesn’t perform any error handling and directly throws the caught error, making it unnecessary. -
By removing useless
catch
clauses, it reduces the potential for mistaken error handling. Developers might leave such clauses with the intention to add error handling later but forget. This rule ensures that only meaningful error handling is present. -
It encourages developers to think critically about their error handling strategy. When this rule flags a
catch
clause, it prompts the developer to consider whether they should be handling the error in a specific way or if the error can be allowed to propagate without catching. -
Implementing this rule can lead to improved performance in some scenarios. Each try-catch block adds a slight overhead to the execution of the code. Removing unnecessary catch blocks, as highlighted by this rule, might have a minimal but positive impact on the performance of the code.
Disallow unnecessary concatenation of literals or template literals
// Example of unnecessarily concatenating literals
const greeting = "Hello, " + "world!";
const date = "The date is: " + "October 1st, 2023";
-
Prevents redundancy in code by disallowing the unnecessary concatenation of string literals or template literals, aiding in simplifying the codebase, making it more readable and maintainable.
-
Enhances performance, albeit marginally, by reducing the operations the JavaScript engine has to perform during string construction, which can be beneficial in scenarios where performance is critical.
-
Improves code clarity and developer experience by enforcing a more straightforward approach to string declaration, making it easier for developers to understand the intention behind the code without the need to decipher unnecessary concatenation logic.
-
Facilitates easier code refactoring and debugging because simpler string expressions are more straightforward to manipulate and less prone to errors introduced during refactoring. This rule helps avoid potential bugs that might arise from complex string concatenations.
Require spread operators instead of .apply()
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum.apply(null, numbers));
-
Using the spread operator (
...
) instead of the.apply()
method, as enforced by this rule, makes the code more succinct and readable. The spread syntax is often more intuitive to understand at a glance, especially for developers who might not be as familiar with the.apply()
method’s purpose and usage. -
By preferring the spread operator over
.apply()
, the rule helps maintain consistency in how functions are called and arguments are passed within a codebase. Consistent coding practices make the code easier to read, maintain, and debug by ensuring that similar tasks are accomplished in similar ways. -
The rule could potentially lead to performance improvements in some JavaScript engines. While modern JS engines are highly optimized for both patterns, the spread operator can sometimes be faster than the equivalent
.apply()
call because it does not have the overhead of setting up a function context when calling.apply()
. -
The
autofix/prefer-spread
rule indirectly encourages developers to use modern JavaScript features, keeping the codebase up-to-date with the latest ECMAScript standards. The spread operator was introduced in ES6 (ECMAScript 2015), and adopting such features may promote the use of other modern JavaScript practices and syntax, contributing to a more modern and efficient codebase.
Enforce the consistent use of the radix argument when using parseInt()
const value = "10";
const number = parseInt(value);
console.log(number);
-
This rule ensures the
parseInt()
function is consistently used with a radix argument, which makes code more predictable by explicitly stating the numeric base that should be used for the conversion process. Without specifying the radix,parseInt()
might lead to unexpected behavior depending on the input string’s format, making the codebase less reliable. -
By enforcing the consistent use of the radix argument, the rule can help prevent subtle bugs that could arise when
parseInt()
interprets strings with leading zeros as octal numbers. This is particularly important when dealing with user input or data that might not always conform to a single format. -
The rule promotes better readability and maintainability of code by making the developer’s intention clear. When a radix is specified, other developers who read the code can easily understand the expected behavior of
parseInt()
, reducing the time spent on understanding code semantics. -
Adoption of this rule assists in making the codebase more uniform, as it aligns the usage of
parseInt()
across all instances. This reduces the cognitive load for developers who work on the codebase, as they can expect a consistent pattern when dealing with numerical string conversion, leading to fewer mistakes and quicker code reviews.
Enforce comparing typeof
expressions against valid strings
let value = 42;
if (typeof value === "integer") { // "integer" is not a valid result for typeof
console.log("Value is a number.");
}
-
This rule prevents errors due to the incorrect use of the
typeof
operator by enforcing comparisons against a set of predefined valid strings, such as “undefined”, “object”, “boolean”, “number”, “string”, “function”, and “symbol”. Comparing the result oftypeof
to an incorrect string, such as “integer” in the example, could lead to unexpected behavior or bugs in the code that are difficult to trace. -
The rule fosters best practices and consistency across the codebase when using
typeof
for type checking. By ensuring that only valid strings are compared against thetypeof
operator’s results, the code is more readable, maintainable, and less prone to typos or misunderstandings regarding JavaScript’s types. -
It directly contributes to code correctness and reliability. By catching invalid comparisons at linting time, it prevents potential runtime errors or logical errors in the application. Since JavaScript will not throw an error for an invalid comparison string, this rule helps identify these issues much earlier in the development process.
-
The rule potentially aids in the optimization of the code. By ensuring that developers use the correct strings when working with
typeof
, it sidesteps unnecessary conditionals or incorrect branches in logic that could otherwise lead to performance inefficiencies or more complex logic than needed. This preemptive correction leads to more optimized and straightforward code execution paths.