JavaScript Coding Violations
Enforce getter/setter Pairs
Description: It's a common mistake in JavaScript to create an object with just a setter for a property but never have a corresponding getter defined for it. Without a getter, you cannot read the property, so it ends up not being used.
let variable = {
set a(value) {
this.val = value;
}
};
let variable = {
set a(value) {
this.val = value;
},
get a() {
return this.val;
}
};
Enforce Line Breaks After Opening and Before Closing Array Brackets.
Description: A number of style guides require or disallow line breaks inside of array brackets.
let a = [];
let b = ["test"];
let c = [[5, 2], 2];
let e = [function boo() {
executesomething();
}];
let a = [
];
let b = [
"test"
];
let c = [
[
5,
2
],
2
];
let e = [
function boo() {
executesomething();
}
];
Disallow or Enforce Spaces Inside of Brackets
Description: A number of style guides require or disallow spaces between array brackets and other tokens. This rule enforces consistent spacing inside array brackets.
let arr = ['fa', 'b' ];
let arr = [ 'a', 'b'];
let arr = [
'a',
'b',
];
Enforces Return Statements
Description: Array
has several methods for filtering, mapping, and folding.
let mapping = variable.reduce(function(a, b, index) {
a[b] = index;
}, {});
let mapping = variable.reduce(function(a, b, index) {
a[b] = index;
return a;
}, {});
Enforce Line Breaks Between Array Elements
Description: A number of style guides require or disallow line breaks between array elements.
let d = [1, 2, 3];
let d = [1,
2,
3];
Require Braces in Arrow Function Body
Description: Arrow functions have two syntactic forms for their function bodies. They may be defined with a block body (denoted by curly braces) () => { ... }
or with a single expression () => ...
, whose value is implicitly returned.
let foo = () => 0;
let a = () => {
return 0;
};
Require Parens in Arrow Function Arguments
Description: Arrow functions can omit parentheses when they have exactly one parameter. In all other cases the parameter(s) must be wrapped in parentheses. This rule enforces the consistent use of parentheses in arrow functions.
a => {};
(a) => {};
Require Space Before/After Arrow Function's Arrow
Description: This rule normalizes the style of spacing before/after an arrow function's arrow(=>
).
(a) =>{};
a =>a;
(a) => {};
a => a;
Treat var as Block Scoped
Description: The block-scoped-var
rule generates warnings when variables are used outside of the block in which they were defined. This emulates C-style block scope.
function condition() {
if (true) {
let a = true;
}
console.log(a);
}
function condition() {
let a;
if (true) {
a = true;
}
console.log(a);
}
Disallow/Enforce Spaces
Description: This rule enforces consistent spacing inside an open block token and the next token on the same line. This rule also enforces consistent spacing inside a close block token and previous token on the same line.
function a() {return true;}
function a() { return true; }
Require Brace Style
Description: Thir rule enforces consistent brace style for blocks
if (a)
{
b();
}
try
{
takeRisks();
} catch(e)
{
doError();
}
if (a) {
b();
}
try {
takeRisks();
} catch(e) {
doError();
}
Enforce Return After Callback
Description: This rule is aimed at ensuring that callbacks used outside of the main function block are always part-of or immediately preceding a return statement.
function a(b, callback) {
if (b) {
callback(b);
}
callback();
}
function a(b, callback) {
if (b) {
return callback(b);
}
callback();
}
Require CamelCase
Description: This rule enforces camelcase naming convention and suggests a consistent code styling approach.
function a({ notincamel: no_camelcased }) {
// ...
}
function a({ isCamelCased: alsoInCamel }) {
// ...
}
Enforce/Disallow Capitalization in Comments
Description: A consistent style can improve a project's maintainability. This rule enforces or disallows capitalization of the first letter of a comment.
// Capitalized comment
// not Capitalized comment
// Capitalized comment
// Capitalized comment as well
Enforce Utilize of this
in Methods
Description: If a class method does not use this
, it can sometimes be made into a static function.
class A {
a() {
console.log("Hello World");
}
}
class A {
a() {
this.bar = "Hello World";
}
}
Require/Disallow Trailing Commas
Description: Trailing commas in object literals are valid according to the ECMAScript 5 (and ECMAScript 3!) spec. However, IE8 (when not in IE8 document mode) and below will throw an error when it encounters trailing commas in JavaScript.
let a = {
b: "b",
c: "c",
};
let arr = [1,2,];
let a = {
b: "b",
c: "c"
};
let arr = [1,2];
Enforces Spacing Around Commas
Description: Spacing around commas improves readability of a list of items. Although most of the style guidelines for languages prescribe adding a space after a comma and not before it, it is subjective to the preferences of a project.
let a = 1 ,b = 2;
let arr = [1 , 2];
let a = 1, b = 2
let arr = [1, 2];
Comma Style
Description: The Comma Style rule enforces styles for comma-separated lists.
let a = 1
,
b = 2;
let a = 1, b = 2;
Limit Cyclomatic Complexity
Description: Cyclomatic complexity measures the number of linearly independent paths through a program's source code. This rule allows setting a cyclomatic complexity threshold.
function a(x) {
if (true) {
return x;
} else if (false) {
return x+1;
} else {
return 0;
}
}
function a(x) {
if (true) {
return x;
} else {
return 0;
}
}
Disallow/Enforce Spaces
Description: While formatting preferences are very personal, a number of style guides require or disallow spaces between computed properties.
let foo = 1
, bar = 2;
let foo = 1,
bar = 2;
Require return
Statements
Description: Unlike statically-typed languages which enforce that a function returns a specified type of value, JavaScript allows different code paths in a function to return different types of values.
function do(condition) {
if (condition) {
return true;
} else {
return;
}
}
function do(condition) {
if (condition) {
return true;
} else {
return false;
}
}
Require Consistent this
Description: This rule enforces consistent naming when capturing the current execution context.
let that;
function f() {
that = this;
}
let that;
that = this;
Require Following Curly Brace Conventions
Description: it is considered by many to be best practice to never omit curly braces around blocks, even when they are optional, because it can lead to bugs and reduces code clarity. This rule requires following curly brace conventions.
if (a) a++;
if (a) {
a++;
}
Require Default Case in Switch Statements
Description: This rule aims to require default case in switch statements. You may optionally include a // no default after the last case if there is no default case.
switch (a) {
case 1:
/* code */
break;
}
switch (a) {
case 1:
/* code */
break;
default:
/* code */
break;
}
Enforce Default Parameters to be Last
Description: Putting default parameter at last allows function calls to omit optional tail arguments.
function f(a = 0, b) {}
function f(a, b = 0) {}
Enforce Newline Before/After dot
Description: Consistency in placing a newline before or after the dot can greatly increase readability.
let a = object.
property;
let foo = object
.property;
Require dot Notation
Description: In JavaScript, one can access properties using the dot notation (foo.bar
) or square-bracket notation (foo["bar"]
). However, the dot notation is often preferred because it is easier to read, less verbose, and works better with aggressive JavaScript minimizers.
let x = a['b'];
let x = a.b;
Require Newline
Description: Trailing newlines in non-empty files are a common UNIX idiom. Benefits of trailing newlines include the ability to concatenate or append to files as well as output files to the terminal without interfering with shell prompts.
function do() {
let a = 2;
}
function do() {
let a = 2;
}
Require === and !==
Description: It is considered good practice to use the type-safe equality operators ===
and !==
instead of their regular counterparts ==
and !=
.
a == undefined
a === undefined
Enforce for Loop
Description: A for loop with a stop condition that can never be reached, such as one with a counter that moves in the wrong direction, will run infinitely. While there are occasions when an infinite loop is intended, the convention is to construct such loops as while loops.
for (let j = 0; j < 50; j--) {
}
for (let i = 200; i >= 100; i++) {
}
for (let j = 0; j < 50; i++) {
}
Disallow Spacing Between Function and Invocations
Description: When calling a function, developers may insert optional whitespace between the function's name and the parentheses that invoke it.
new a();
new a ();
new a();
new a();
Require Match of Function Names
Description: This rule requires function names to match the name of the variable or property to which they are assigned.
Object.create(obj, {a:{value: function b() {}}});
Object.create(obj, {a:{value: function a() {}}});
Disallow Named function
Expressions
Description: A pattern that's becoming more common is to give function expressions names to aid in debugging.
A.prototype.b = function b() {};
(function b() {
// ...
}())
A.prototype.b = function() {};
(function() {
// ...
}())
Enforce Use of Declarations or Expressions
Description: There are two ways of defining functions in JavaScript: function
declarations and function
expressions. Declarations contain the function
keyword first, followed by a name and then its arguments and the function body.
function a() {
// ...
}
let a = function() {
// ...
};
let a = () => {};
Enforce Line Breaks Between Arguments
Description: A number of style guides require or disallow line breaks between arguments of a function call.
a("one", "two",
"three");
a(
"one",
"two",
"three"
);
Enforce Line Breaks in Function Parentheses
Description: Many style guides require or disallow newlines inside of function parentheses.
function a(b, c) {}
function a(
b,
c
) {}
Enforce Spacing Around the * in Generator Functions
Description: Generators are a new type of function in ECMAScript 6 that can return multiple values over time.
function * generator() {}
let anonymous = function* () {};
let shorthand = { *generator() {} };
class Class { static* method() {} }
function* generator() {}
let anonymous = function*() {};
let shorthand = { * generator() {} };
class Class { static * method() {} }
Enforce return Statement for getters
Description: The get syntax binds an object property to a function that will be called when that property is looked up.
p = {
get a(){
// no returns.
}
};
p = {
get a(){
return 'b';
}
};
Require Grouped Accessor Pairs
Description: A getter and setter for the same property don't necessarily have to be defined adjacent to each other.
let dummy = {
get a() {
return this.val;
},
b: 1,
set a(value) {
this.val = value;
}
};
let dummy = {
get a() {
return this.val;
},
set a(value) {
this.val = value;
},
b: 1
};
Require Guarding for-in
Description: Looping over objects with a for in
loop will include properties that are inherited through the prototype chain. This behavior can lead to unexpected items in your for loop.
for (key in a) {
do(key);
}
for (key in a) {
if (Object.prototype.hasOwnProperty.call(a, key)) {
do(key);
}
}
Enforce Callback Error Handling
Description: In Node.js, a common pattern for dealing with asynchronous behavior is called the callback pattern.
function load (err, b) {
do();
}
function load (err, b) {
if (err) {
console.log(err.stack);
}
do();
}
Disallow Specified Identifiers
Description: Generic names can lead to hard-to-decipher code. This rule allows you to specify a deny list of disallowed identifier names to avoid this practice.
class A {
callback();
}
class A {
method();
}
Enforce Minimum and Maximum Identifier Lengths
Description: Very short identifier names like e
, x
, _t
or very long ones like hashGeneratorResultOutputContainerObject
can make code harder to read and potentially less maintainable. To prevent this, one may enforce a minimum and/or maximum identifier length.
let x = 5;
let name = 5;
Require Identifiers Match Expression
Description: This rule allows you to precisely define and enforce the variables and function names that should be used.
class first_Class {}
class firstClass {
do() {}
}
class firstClass {}
class firstClass {
do() {}
}
Enforce Location of Arrow Function Bodies
Description: An arrow function body can contain an implicit return as an expression instead of a block body. It can be useful to enforce a consistent location for the implicitly returned expression.
(a) =>
b;
(a) => b;
Enforce Consistent Indentation
Description: There are several common guidelines which require specific indentation of nested blocks and statements.
if (a) {
b=c;
function fun(d) {
e=f;
}
}
if (a) {
b=c;
function fun(d) {
e=f;
}
}
Require Initialization in Variable Declarations
Description: In JavaScript, variables can be assigned during declaration, or at any point afterwards using an assignment statement. For example, in the following code, foo
is initialized during declaration, while bar
is initialized later.
function a() {
let b;
let c;
}
function a() {
let b = 1;
let c = 2;
const qux = 3;
}
Enforce Consistent Use of Double Quotes
Description: JSX attribute values can contain string literals, which are delimited with single or double quotes.
<a b='car' />
<a b="car" />
Enforce Consistent Spacing Between Keys and Values
Description: This rule enforces spacing around the colon in object literal properties. It can verify each property individually, or it can ensure horizontal alignment of adjacent properties in an object literal.
let obj = { 'a' : 42 };
let obj = { 'a': 42 };
Enforce Consistent Spacing Before/After Keywords
Description: Keywords are syntax elements of JavaScript, such as try
and if
.
if (a) {
//...
}else if (b) {
//...
}else {
//...
}
if (a) {
//...
} else if (b) {
//...
} else {
//...
}
enforce position of line comments
Description: Line comments can be positioned above or beside code. This rule helps teams maintain a consistent style.
1 + 1; // invalid comment
// valid comment
1 + 1;
Enforce Consistent Linebreak Style
Description: This rule enforces consistent line endings independent of operating system, VCS, or editor used across your codebase.
let a = 'a'; // CRLF
let a = 'a', // LF
b = 'b'; // LF
// LF
Require Empty Lines Around Comments
Description: Many style guides require empty lines before or after comments. The primary goal of these rules is to make the comments easier to read and improve readability of the code.
let a = "b";
/* what a great and wonderful day */
let c = "d"
let a = "b";
/* what a great and wonderful day */
let c = "d"
Require Newlines Around Directives
Description: This rule requires or disallows blank newlines around directive prologues. This rule does not enforce any conventions about blank newlines between the individual directives. In addition, it does not require blank newlines before directive prologues unless they are preceded by a comment.
"use strict";
let a;
"use strict";
let a;
Require an Empty Line Between Class Members
Description: This rule improves readability by enforcing lines between class members. It will not check empty lines before the first member and after the last member, since that is already taken care of by padded-blocks.
class Alpha{
x;
yvar(){}
zvar(){}
}
class Alpha{
x;
yvar(){}
zvar(){}
}
Enforce a Maximum Number of Classes per File
Description: Files containing multiple classes can often result in a less navigable and poorly structured codebase. Best practice is to keep each file limited to a single responsibility.
class dummyA {}
class dummyB {},
class dummyC {}
class dummyA {}
Enforce a Maximum Depth of Nesting Blocks
Description: Many developers consider code difficult to read if blocks are nested beyond a certain depth.
function alpha() {
for (;;) { // Nested 1 deep
while (true) { // Nested 2 deep
if (true) { // Nested 3 deep
if (true) { // Nested 4 deep
if (true) { // Nested 5 deep
}
}
}
}
}
}
function alpha() {
for (;;) { // Nested 1 deep
while (true) { // Nested 2 deep
if (true) { // Nested 3 deep
if (true) { // Nested 4 deep
}
}
}
}
}
Enforce a Maximum Line Length
Description: Very long lines of code in any language can be difficult to read. In order to aid in readability and maintainability many coders have developed a convention to limit lines of code to a specific number of characters.
let a = { "a" : "This is a long string, which is used as values of an object's a key", "b" : "This is a long string, which is used as values of an object's b key" };
let a = {
"a" : "This is a long string, which is used as values of an object's a key",
"b" : "This is a long string, which is used as values of an object's b key"
};
Enforce a Maximum Function Length
Description: Many coding style guides dictate a limit of the number of lines that a function can comprise of. This rule can help enforce that style.
Enforce a Maximum File Length
Description: Large files tend to do a lot of things and can make it hard following what's going. While there is not an objective maximum number of lines considered acceptable in a file, it is agreed that it should not be in the thousands. Recommendations usually range from 100 to 500 lines.
Enforce a Maximum Depth of Nesting Callbacks
Description: This rule enforces a maximum depth that callbacks can be nested to increase code clarity.
// Examples of incorrect code for this rule with maximum of 3 levels of nesting:
alpha1(function() {
alpha2(function() {
alpha3(function() {
alpha4(function() {
// Do something
});
});
});
});
// Examples of correct code for this rule with maximum of 3 levels of nesting:
function doAlpha1() {
alpha2(doAlpha2);
}
function doAlpha2() {
alpha3(doAlpha3);
}
Enforce a Maximum Number of Parameters
Description: Functions that take numerous parameters can be difficult to read and write because it requires the memorization of what each parameter is, its type, and the order they should appear in.
// Examples of incorrect code for this rule with the default maximum of 3 params:
function alpha (b, c, d, e) {
do();
}
// Examples of correct code for this rule with the default maximum of 3 params:
function alpha (b, c, d) {
do();
}
Enforce a Maximum Number of Statements per Line
Description: A line of code containing too many statements can be difficult to read.
// Examples of incorrect code for this rule with the default maximum of 1 statement:
let b; let c;
if (condition) { c = 1; }
// Examples of correct code for this rule with the default maximum of 1 statement:
let b, c;
if (condition) c = 1;
Enforce a Maximum Number of Statements in Function Blocks
Description: The max-statements
rule allows you to specify the maximum number of statements allowed in a function.
// Examples of incorrect code for this rule with the default maximum 2 statements:
function alpha() {
let alpha1 = 1;
let alpha2 = 2;
let alpha3 = 3;
}
// Examples of correct code for this rule with the default maximum 2 statements:
function alpha() {
let alpha1 = 1;
let alpha2 = 2;
}
Enforce a Particular Style for Multiline Comments
Description: Many style guides require a particular style for comments that span multiple lines.
// Example of incorrect code for this rule with the default "starred-block" style of comments:
// this line
// calls alpha()
alpha();
// Example of correct code for this rule with the default "starred-block" style of comments:
/*
* this line
* calls alpha()
*/
alpha();
Enforce Newlines Ternary Expressions
Description: This rule enforces newlines between operands of a ternary expression.
a > b ? value1 : value2;
a > b ?
value1 :
value2;
Require Constructor Names with Capital Letter
Description: It is required that constructor names begin with a capital letter. Certain built-in identifiers are exempt from this rule.
let alpha = new beta();
let alpha = new Beta();
Require Parentheses When Invoking a Constructor
Description: It can enforce or disallow parentheses when invoking a constructor with no arguments using the new keyword.
let alpha = new (Beta);
let alpha = new Beta();
Require Empty Line after Declarations
Description: This enforces a coding style where empty lines are required or disallowed after var, let, or const statements to achieve a consistent coding style across the project.
let alpha = "apple,",
beta = "ball";
console.log(alpha, beta);
let alpha = "apple,",
beta = "ball";
console.log(alpha, beta);
Require Empty Line Before Return
Description: It is required to have an empty line before return statements to increase code clarity, except when the return is alone inside a statement group (such as an if statement).
function alpha(beta) {
if (!beta) {
return;
}
return beta;
}
function alpha() {
return;
}
Require Newline after Each Call
Description: This rule requires a newline after each call in a method chain or deep member access.
_.chain({}).map(alpha).filter(beta).value();
_
.chain({})
.map(alpha)
.filter(beta)
.value();
Disallow Use of Alert
Description: This is aimed at catching debugging code that should be removed and popup UI elements that should be replaced with less obtrusive, custom UIs.
alert("Warning");
customAlert("Do!");
Disallow Array Constructors
Description: It prevents Array constructors.
new Array(1, 2, 3)
new Array(arrayTwo.length)
Disallow Using Async Function
Description: This dismisses async Promise executor functions.
const result = new Promise(async (resolve, reject) => {
resolve(await alpha);
}
);
const result = Promise.resolve(alpha);
Disallow Await Inside Loops
Description: This rule disallows the use of await within loop bodies.
for (const alpha of alphas) {
results.push(await beta(alpha));
}
return theta(results);
for (const alpha of alphas) {
results.push(beta(alpha));
}
return theta(await Promise.all(results));
Disallow Bitwise Operators
Description: It prevents bitwise operators.
let a = b | c;
let a = b || c;
Disallow Use of Buffer Constructor
Description: It disallows calling and constructing the Buffer() constructor.
new Buffer(res.alpha.beta);
new Buffer(res.alpha.theta);
Buffer.alloc(res.alpha.beta);
Buffer.from(res.alpha.theta);
Disallow Use of Caller Callee
Description: It discourages the use of deprecated and sub-optimal code by disallowing the use of arguments.caller and arguments.callee.
function alpha(m) {
if (m <= 0) {
return;
}
arguments.callee(m - 1);
}
function alpha(m) {
if (m <= 0) {
return;
}
foo(m - 1);
}
Disallow Lexical Declarations
Description: It prevents access to uninitialized lexical bindings as well as accessing hoisted functions across case clauses.
switch (alpha) {
case 1:
let a = 1;
break;
case 2:
const b = 2;
break;
case 3:
function f() {}
break;
default:
class H {}
}
Disallow Shadowing of Inside Catch
Description: This will warn whenever it encounters a catch clause parameter that has the same name as a variable in an outer scope.
let err = "a";
try {
throw "warning";
} catch (err) {
}
let err = "a";
try {
throw "warning";
} catch (e) {
}
Disallow Modifying Variables
Description: It flags modifying variables of class declarations.
class X { }
X = 0;
let X = class X { }
X = 0;
Disallow Comparing Against -0
Description: This warns against code that tries to compare against -0, since that will not work as intended.
if (a === -0) {
// do()...
}
if (a === 0) {
// do()...
}
Disallow Assignment Operators
Description: It disallows ambiguous assignment operators in test conditions of if, for, while, and do...while statements.
let a;
if (a = 0) {
let x = 1;
}
let a;
if (a === 0) {
let x = 1;
}
Disallow Arrow Functions
Description: It is not allowed to use arrow functions where they could be confused with comparisons.
let a = x => 4 ? 5 : 6;
let a = x => (4 ? 5 : 6);
Disallow Use of Console`
Description: This prevents calls or assignments to methods of the console object.
console.log("A message");
// custom console
Console.log("This is a message");
Disallow Modifying Variables Using Const
Description: This is aimed to flag modifying variables that are declared using const keyword.
const vav = 0;
vav += 1;
const vav = 0;
console.log(vav);
Disallow Constant Expressions in Conditions
Description: According to this rule, it is not allowed constant expressions in the test condition.
if (void a) {
doWhatIsNotFinished();
}
if (a &&= false) {
doThisNever();
}
if (a === 5) {
doThis();
}
while (typeof a === "undefined") {
doThis();
}
Disallow Returning Value in Constructor
Description: This prevents return statements in the constructor of a class.
class C {
constructor(c) {
this.c = c;
return c;
}
}
class C {
constructor(c) {
this.c = c;
}
}
Disallow Continue Statements
Description: This disallows continue statements.
for(i = 0; i < 5; i++) {
if(i >= 3) {
continue;
}
a += i;
}
for(i = 0; i < 5; i++) {
if(i < 3) {
a += i;
}
}
Disallow Control Characters
Description: It is not allowed control characters in regular expressions.
let expression1 = /ÿ/;
let expression2 = new RegExp("ÿ");
let expression1 = /,/;
let expression2 = new RegExp(",");
Disallow the Use of Debugger
Description: It is suggested not to use debugger statements.
function isReal(x) {
debugger;
return true;
}
function isReal(x) {
return true; // add a breakpoint here
}
Disallow Deleting Variables
Description: The use of the delete operator on variables is not allowed.
let x;
delete x;
Disallow Regular Expressions That Look Like Division
Description: This is used to disambiguate the division operator to not confuse users.
function beta() { return /=alpha/; }
function beta() { return /[=]alpha/; }
Disallow Duplicate Arguments in Function
Description: Duplicate parameter names in function declarations or expressions are not permitted. It does not apply to arrow functions or class methods, because the parser reports the error.
function alpha(x, y, x) {
console.log("value of the second x:", x);
}
function alpha(x, y, z) {
console.log(x, y, z);
}
Disallow Duplicate Name in Class Members
Description: This flags the use of duplicate names in class members.
class Boo {
bob() { }
get bob() { }
}
class Boo {
get bob() { }
set bob(value) { }
}
Disallow Duplicate Conditions in if-else-if
Description: It is not allowed to use duplicate conditions in the same if-else-if chain.
if (test(x)) {
boo();
} else if (test(x)) {
bob();
}
if (first(x)) {
boo();
} else if (second(x)) {
bob();
}
Disallow Duplicate Keys
Description: This rule disallows duplicate keys in object literals.
let boo = {
var: "abc",
var: "cba"
};
let boo = {
"var": "abc",
var: "cba"
};
let boo = {
var: "abc",
var2: "cba"
};
Disallow Duplicate Case Labels
Description: Duplicate test expressions in case clauses of switch statements are not allowed.
let x = 5;
switch (x) {
case one:
console.log(4);
break;
case two:
console.log(3);
break;
case one:
console.log(2);
break;
default:
console.log(1);
break;
}
let x = 5;
switch (x) {
case one:
console.log(4);
break;
case two:
console.log(3);
break;
case three:
console.log(2);
break;
default:
console.log(1);
break;
}
Disallow duplicate imports
Description: It is required that all imports from a single module that can be merged exist in a single import statement.
import { alpha } from 'module';
import { beta } from 'module';
import { alpha, beta } from 'module';
Disallow Return before Else
Description: It highlights an unnecessary block of code following an if containing a return statement. As such, it will warn when it encounters an else following a chain of ifs, all of them containing a return statement.
function alpha() {
if (a) {
return b;
} else {
return c;
}
}
function alpha() {
if (a) {
return b;
}
return c;
}
Disallow Empty Character Classes
Description: This rule disallows empty character classes in regular expressions.
/^xyz[]/.test("xyzpoi");
"xyzpoi".match(/^xyz[]/);
/^xyz/.test("xyzpoi");
"xyzpoi".match(/^xyz/);
Disallow Empty Functions
Description: This eliminates empty functions. A function will not be considered a problem if it contains a comment.
function alpha() {}
function alpha() {
// do nothing.
}
Disallow Empty Destructuring Patterns
Description: This flags any empty patterns in destructured objects and arrays, and as such, will report a problem whenever one is encountered.
let {b: {}} = alpha;
let {b: { c }} = alpha;
disallow empty block statements
Description: Empty block statements are not permitted. This rule ignores block statements which contain a comment (for example, in an empty catch or finally block of a try statement to indicate that execution should continue regardless of errors).
if (alpha) {
}
if (alpha) {
//do Nothing
}
Disallow Null Comparisons
Description: The no-eq-null rule aims reduce potential bug and unwanted behavior by ensuring that comparisons to null only match null, and not also undefined. As such it will flag comparisons to null when using == and !=.
if (alpha == null) {
beta();
}
if (alpha === null) {
beta();
}
Disallow Eval
Description: This prevents potentially dangerous, unnecessary, and slow code by disallowing the use of the eval() function. As such, it will warn whenever the eval() function is used.
let obj = { a: "alpha" },
key = "a",
value = eval("obj." + key);
let obj = { a: "alpha" },
key = "a",
value = obj[key];
Disallow Reassigning Exceptions in Catch
Description: It is not permitted to reassign exceptions in catch clauses.
try {
// doSomething
} catch (e) {
e = 5;
}
try {
// doSomething
} catch (e) {
let alpha = 5;
}
Disallow Extending of Native Objects
Description: Disallows directly modifying the prototype of builtin objects.
Object.prototype.alpha = 'a';
Object.defineProperty(Array.prototype, "times", { value: 100 });
Object.prototype.alpha = 'a';
Disallow Unnecessary Function Binding
Description: This avoids the unnecessary use of bind() and as such will warn whenever an immediately-invoked function expression (IIFE) is using bind() and doesn't have an appropriate this value. This rule won't flag usage of bind() that includes function argument binding.
let a = function () {
alpha();
}.bind(beta);
let a = function () {
this.alpha();
}.bind(beta);
Disallow Unnecessary Boolean Casts
Description: It disallows unnecessary boolean casts.
let alpha = !!!beta;
let alpha = Boolean(!!beta);
let alpha = !!beta;
let alpha = Boolean(beta);
Disallow Unnecessary Labels
Description: This eliminates unnecessary labels.
B: while (b) {
break B;
}
while (b) {
break;
}
Disallow Unnecessary Parentheses
Description: This restricts the use of parentheses to only where they are necessary.
(function(){} ? x() : y());
(function(){}) ? x() : y();
Disallow Unnecessary Semicolons
Description: This prevents unnecessary semicolons.
function foo() {
// doSomething
};
function foo() {
// doSomething
}
Disallow Case Statement Fallthrough
Description: This eliminates unintentional fallthrough of one case to the other. As such, it flags any fallthrough scenarios that are not marked by a comment.
switch(alpha) {
case 1:
doSome();
case 2:
doSome();
}
switch(alpha) {
case 1:
doSome();
break;
case 2:
doSome();
}
Disallow Floating Decimals
Description: This discards floating decimal points and will warn whenever a numeric value has a decimal point but is missing a number either before or after it.
let num = .8;
let num = 0.8;
Disallow Reassigning Function
Description: Reassigning function declarations is not permitted.
function alpha() {}
alpha = beta;
let alpha = function () {}
alpha = beta;
Disallow Assignment to Native Objects
Description: This rule disallows modifications to read-only global variables.
Object = null
undefined = 1
x = 1
let y = 1
y = 2
Disallow Shorthand Type Conversions
Description: This indicates shorter notations for the type conversion, then suggest a more self-explanatory notation.
let a = !!beta;
let a = ~beta.indexOf(".");
let a = Boolean(beta);
let a = beta.indexOf(".") !== -1;
let n = ~beta;
Disallow Declarations in the Global Scope
Description: This disallows var and function declarations at the top-level script scope. This does not apply to ES and CommonJS modules since they have a module scope.
var alpha = 1;
function beta() {}
window.alpha = 1;
window.beta = function () {};
Disallow Implied eval
Description: This eliminates implied eval() through the use of setTimeout(), setInterval() or execScript(). As such, it will warn when either function is used with a string as the first argument.
setTimeout("alert('Hello');", 50);
setTimeout(function() {
alert("Hello");
}, 50);
Disallow Assigning to Imported Bindings
Description: This warns the assignments, increments, and decrements of imported bindings.
import alpha, { beta } from "./delta.mjs"
alpha = 1
beta = 'b'
import alpha, { beta } from "./delta.mjs"
alpha.prop = 1
beta.prop = 'b'
Disallow Inline Comments after Code
Description: Comments on the same line as code are not allowed.
let x = 1; // declaring x
// Comment above
let alpha = a;
Disallow Variable or Function in Nested Blocks
Description: It is required that function declarations and, optionally, variable declarations be in the root of a program, or in the root of the body of a function, or in the root of the body of a class static block.
if (alpha) {
function beta() { }
}
function beta() { }
Disallow Invalid Regular Expression Strings in RegExp
Description: This rule disallows invalid regular expression strings in RegExp constructors.
RegExp('[')
RegExp('.')
Disallow Use of This in Contexts where is Undefined
Description: It flags usage of this keywords in contexts where the value of this is undefined.
alpha(function() {
this.x = 0;
beta(() => this);
});
class Alpha {
constructor() {
this.x = 0;
beta(() => this);
}
}
Disallow Irregular Whitespace
Description: It is aimed at catching invalid whitespace that is not a normal tab and space. Some of these characters may cause issues in modern browsers and others will be a debugging issue to spot.
function thing() /*<NBSP>*/{
return 'test';
}
function thing() {
return 'test';
}
Disallow Iterator
Description: It is preventing errors that may arise from using the iterator property, which is not implemented in several browsers. As such, it will warn whenever it encounters the iterator property.
foo.__iterator__ = function () {};
let __iterator__ = foo;
Disallow Labels that are Variables Names
Description: This creates clearer code by disallowing the bad practice of creating a label that shares a name with a variable that is in scope.
let a = alpha;
function beta() {
a:
for (;;) {
break a;
}
}
function alpha() {
let x = y;
}
function beta() {
x:
for(;;) {
break x;
}
}
Disallow Labeled Statements
Description: It aims to eliminate the use of labeled statements in JavaScript. It will warn whenever a labeled statement is encountered and whenever break or continue are used with a label.
label:
while(true) {
break label;
}
while (true) {
break;
}
Disallow Unnecessary Nested Blocks
Description: It eliminates unnecessary and potentially confusing blocks at the top level of a script or within other blocks.
if (alpha) {
beta();
{
theta();
}
}
if (alpha) {
if (beta) {
theta();
}
}
Disallow If Statements as the Only Statement in Else
Description: It is suggested to prevent if statements as the only statement in else blocks.
if (condition) {
// doSomething
} else {
if (anotherCond) {
// doSomething
}
}
if (condition) {
// doSomething
} else if (anotherCond) {
// doSomething
}
Disallow Functions in Loops
Description: It is required to disallow any function within a loop that contains unsafe references (e.g. to modified variables from the outer scope).
for (let i=5; i; i--) {
(function() { return i; })();
}
let b = function() {};
for (let i=5; i; i--) {
b();
}
Disallow Magic Numbers
Description: The no-magic-numbers aims to make code more readable and refactoring easier by ensuring that special numbers are declared as constants to make their meaning explicit.
let startP = 50,
finalP = startP + (startP * 0.1);
const T = 0.1;
let startP = 50,
finalP = startP + (startP * T);
Disallow Characters with Multiple Code Points
Description: Τhe regular expressions are reported which include multiple code point characters in character class syntax.
/^[Á]$/u
/^[abc]$/
Disallow Mixes of Different Operators
Description: This rule checks BinaryExpression, LogicalExpression and ConditionalExpression.
let alpha = x && y < 0 || z > 0 || a + 1 === 0;
let alpha = (x && y < 0) || z > 0 || a + 1 === 0;
Disallow Require Calls with Regular Variable Declarations
Description: This prevents require calls to be mixed with regular variable declarations.
let alpha = {
set a(value) {
this.val = value;
return value;
}
};
let alpha = {
set a(value) {
this.val = value;
}
};
Disallow Mixed Spaces and Tabs
Description: This disallows mixed spaces and tabs for indentation.
function add(a, b) {
// --->..return a + b;
return a + b;
}
function add(a, b) {
// --->return a + b;
return a + b;
}
Disallow Use of Chained Assignment Expressions
Description: It disallows using multiple assignments within a single statement.
let x = y = z = 1;
let x = 1;
let y = 1;
let z = 1;
Disallow Multiple Spaces
Description: This aims to disallow multiple whitespace around logical expressions, conditional expressions, declarations, array elements, object properties, sequences and function parameters.
if(alpha === "beta") {}
if(alpha === "beta") {}
Disallow Multiline Strings
Description: This rule is aimed at preventing the use of multiline strings.
let a = "text \
and other text";
let a = "text and other text";
Disallow Multiple Empty Lines
Description: This aims to reduce the scrolling required when reading through your code. It will warn when the maximum amount of empty lines has been exceeded.
let alpha = 1;
let beta = 2;
let alpha = 1;
let beta = 2;
Disallow Reassignment of Native Objects
Description: It disallows modifications to read-only global variables.
Object = null
undefined = 1
Disallow Negated Conditions
Description: This rule disallows negated conditions.
if (!b) {
doSome();
} else {
doElse();
}
if (b) {
doElse();
} else {
doSome();
}
Disallow Negating the Left Operand in In
Description: It disallows negating the left operand in in expressions.
if(!key in object) {
// doSomething
}
if(!(key in object)) {
// doSomething
}
Disallow Nested Ternary Expressions
Description: The no-nested-ternary rule disallows nested ternary expressions.
let alpha = beta ? theta : zeta === xyz ? xyzz : betatheta;
let alpha = beta ? theta : betatheta;
Disallow Function Constructor
Description: This error is raised to highlight the use of a bad practice. By passing a string to the Function constructor, you are requiring the engine to parse that string much in the way it has to when you call the eval function.
let a = new Function("x", "y", "return x + y");
let a = function (x, y) {
return x + y;
};
Disallow Object Constructors
Description: This rule disallows Object constructors.
let newObject = new Object();
Disallow New Operators with Require
Description: This aims to eliminate use of the new require expression.
let appHeader = new require('app-header');
let AppHeader = require('app-header');
let appHeader = new AppHeader();
Disallow Symbol Constructor
Description: It is suggested to prevent the accidental calling of Symbol with the new operator.
let boo = new Symbol('boo');
let boo = Symbol('boo');
Disallow Primitive Wrapper Instances
Description: This is required to eliminate the use of String, Number, and Boolean with the new operator. As such, it warns whenever it sees new String, new Number, or new Boolean.
let stringObject = new String("Alert");
let text = String(testValue);
Disallow new For Side Effects
Description: This is aimed at maintaining consistency and convention by disallowing constructor calls using the new keyword that do not assign the resulting object to a variable.
new Alpha();
let alpha = new Alpha();
Disallow Calling Global Object Properties as Functions
Description: It is suggested not to call the Math, JSON, Reflect and Atomics objects as functions. This rule also disallows using these objects as constructors with the new operator.
let newAlpha = new Alpha();
let test = Alpha.load(beta, 0);
Disallow Octal Escape Sequences
Description: It is required to disallow octal escape sequences in string literals.
let alpha = "Copyright \251";
let foo = "Copyright \u00A9";
Disallow Octal Literals
Description: The rule disallows octal literals.
let num = 071;
let num = "071";
Disallow Reassignment of Function Parameters
Description: This is aimed to prevent unintended behavior caused by modification or reassignment of function parameters.
function alpha(beta) {
beta = 1;
}
function alpha(beta) {
let theta = beta;
theta = 1;
}
Disallow String Concatenation
Description: This is suggested to prevent string concatenation of directory paths in Node.js
let newPath = __dirname + "/alpha.js";
Disallow the Unary Operators
Description: It is prevented to use the unary operators ++ and --.
let alpha = 0;
alpha++;
let alpha = 0;
alpha += 1;
Disallow Process.env
Description: It is suggested to aim at discouraging use of process.env to avoid global dependencies. As such, it will warn whenever process.env is used.
if(process.env.NODE_ENV === "development") {
//doSomething
}
let config = require("./config");
if(config.env === "development") {
//doSomething
}
Disallow Process.exit
Description: It prevents the use of process.exit() in Node.js JavaScript. As such, it warns whenever process.exit() is found in code.
process.exit(1);
process.exit(0);
Disallow Use of proto
Description: When an object is created with the new operator, proto is set to the original prototype property of the object's constructor function. Object.getPrototypeOf is the preferred method of getting the object's prototype.
let x = obj.__proto__;
let x = Object.getPrototypeOf(obj);
Disallow Use of Object.prototypes Builtins
Description: The call of some Object.prototype methods directly is prevented on object instances.
let hasBeta = alpha.hasOwnProperty("beta");
let hasBeta = Object.prototype.hasOwnProperty.call(alpha, "beta");
Disallow Variable Redeclaration
Description: This rule is aimed at eliminating variables that have multiple declarations in the same scope.
let x = 1;
let x = 5;
let x = 1;
x = 5;
Disallow Multiple Spaces in Regular Expression
Description: It is suggested not to use multiple spaces in regular expression literals.
let reg = /alpha beta/;
let reg = new RegExp("alpha beta");
let reg = /alpha {3}beta/;
let reg = new RegExp("alpha {3}beta");
Disallow Specific Global Variables
Description: This allows you to specify global variable names that you don't want to use in your application.
function onClick() {
console.log(event);
}
import event from "event-module";
Disallow Specific Imports
Description: It is allowed to specify imports that you don't want to use in your application.
import fs from 'fs';
Disallow Node.js Modules
Description: It is permitted to specify modules that you don't want to use in your application.
let fs = require('fs');
let cluster = require('cluster');
Disallow Certain Object Properties
Description: This rule looks for accessing a given property key on a given object name, either when reading the property's value or invoking it as a function.
Disallow Specified Syntax
Description: This rule disallows specified (that is, user-defined) syntax.
let doThis = function () {};
alpha in beta;
function doThis() {};
alpha instanceof beta;
Disallow Assignment in return Statement
Description: This aims to eliminate assignments from return statements. As such, it will warn whenever an assignment is found as part of return.
function doThing() {
return alpha += 2;
}
Disallows Unnecessary return await
Description: Unnecessary return await should not be allowed.
async function alpha() {
return await beta();
}
async function alpha() {
return beta();
}
Disallow Script URLs
Description: Script URLs should not be allowed
location.href = "javascript:void(0)";
Disallow Self Assignment
Description: Self assignments have no effect, so probably those are an error due to incomplete refactoring.
alpha = alpha;
alpha = beta;
Disallow Self Compare
Description: Comparisons where both sides are exactly the same is not allowed.
let alpha = 10;
if (alpha === alpha) {
x = 20;
}
Disallow Use of the Comma Operator
Description: The use of the comma operator. is not allowed.
alpha = do(), val;
alpha = (do(), val);
Disallow Returning Values from Setters
Description: Returning values from setters and reports return statements in setter functions is not allowed.
let alpha = {
set a(value) {
this.val = value;
return value;
}
};
let alpha = {
set a(value) {
this.val = value;
}
};
Disallow Shadowing of Restricted Names
Description: Identifiers from shadowing restricted names are not allowed
function NaN(a, b){}
function f(a, b){}
Disallow Variable Declarations from Shadowing Variables
Description: This rule aims to eliminate shadowed variable declarations.
let alpha = 3;
function beta() {
let alpha = 10;
}
Disallow Spacing Between Function Identifiers
Description: This rule disallows spacing between function identifiers and their applications.
fn ()
fn()
Disallow Sparse Arrays
Description: This rule disallows sparse array literals which have gaps where commas are not preceded by elements.
let items = [,];
let items = [];
Disallow Synchronous Methods
Description: The synchronous methods are not allowed.
fs.existsSync(myPath);
function alpha() {
let result = fs.readFileSync(myPath).toString();
}
obj.sync();
async(function() {
// ...
});
Disallow All Tabs
Description: Some style guides don't allow the use of tab characters at all, including within comments.
let a = 2;
let a = 2;
Disallow Template Literal Placeholder Syntax
Description: The template literal placeholder syntax in regular strings is disallowed.
"Hello ${name}!";
`Hello ${name}!`;
Disallow Ternary Operators
Description: The ternary operator is used to conditionally assign a value to a variable. Some believe that the use of ternary operators leads to unclear code.
let alpha = boolean ? b : c;
let alpha;
if (boolean) {
alpha = b;
} else {
alpha = c;
}
Disallow Use of this/super Before Calling super
Description: The use of this/super before calling super() in constructors is disallowed.
class A extends B {
constructor() {
this.a = 0;
super();
}
}
class A {
constructor() {
super();
this.a = 0;
}
}
Restrict what can be Thrown as an Exception
Description: There should be consistency when throwing exception by disallowing to throw literals and other expressions which cannot possibly be an Error object.
throw "error";
throw new Error();
Disallow Trailing Whitespace at the End of Lines
Description: Trailing whitespace (spaces, tabs, and other Unicode whitespace characters) at the end of lines is not allowed.
let alpha = 0;//•••••
let alpha = 0;
Disallow Initializing to Undefined
Description: Initializing variables to undefined is prohibited.
let alpha = undefined;
let alpha;
Disallow Undeclared Variables
Description: the use of undeclared variables unless mentioned in global comments is disallowed.
let boo = yourFunction();
let tab = a + 1;
// globally declared a
let foo = someFunction();
let bar = a + 1;
Disallow Use of undefined Variable
Description: The use of undefined should be eliminated, and as such, generates a warning whenever it is used.
let undefined = 15;
let x = 15;
Disallow Dangling Underscores in Identifiers
Description: As far as naming conventions for identifiers go, dangling underscores may be the most polarizing in JavaScript. Dangling underscores are underscores at either the beginning or end of an identifier, such as:
let alpha;
let alpha = __beta;
Disallow Confusing Multiline Expressions
Description: Confusing multiline expressions should be disallowed.
let alpha = beta
(1 || 2).beta();
Disallow Unmodified Conditions of Loops
Description: This rule finds references which are inside of loop conditions, then checks the variables of those references are modified in the loop.
let alpha = something;
while (alpha) {
do(alpha);
alpha = alpha.width;
}
Disallow Ternary Operators
Description: Ternary operators when simpler alternatives exist are disallowed
ar a = x === 2 ? true : false;
Disallow Unreachable Code after Statements
Description: Unreachable code after return, throw, continue, and break statements is disallowed.
function alpha() {
return true;
console.log("ok");
}
function alpha() {
console.log("ok");
return true;
}
Disallow Control Flow Statements in finally Blocks
Description: Control flow statements in finally blocks is disallowed.
let alpha = function() {
try {
return 1;
} catch(err) {
return 2;
} finally {
return 3;
}
};
let alpha = function() {
try {
return 1;
} catch(err) {
return 2;
} finally {
console.log("hi!");
}
};
Disallow Negating the Left Operand of Relational Operators
Description: Negating the left operand of the following relational operators should be disallowed.
if (!key in object) {
}
if (!(key in object)) {
}
Disallow Unused Expressions
Description: An unused expression which has no effect on the state of the program indicates a logic error.
if(0) 0;
if(true) execute();
Disallow Unused Labels
Description: Labels that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring.
A: let alpha = 0;
A: {
if (alpha()) {
break A;
}
bar();
}
Disallow Unused Variables
Description: Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring.
let alpha;
const beta = 10;
console.log(beta);
const alpha = 5;
const beta = 10;
console.log(alpha, beta);
Disallow Early Use
Description: Variables should be used after their declaration.
console.log(a);
const a = 10;
const a = 10;
console.log(a);
Disallow Unnecessary .call
Description: This rule is aimed to flag usage of Function.prototype.call() and Function.prototype.apply() that can be replaced with the normal function invocation.
alpha.call(undefined, 1, 2, 3);
alpha.call(obj, 1, 2, 3);
Disallow Unnecessary Catch Clauses
Description: This rule reports catch clauses that only throw the caught error.
try {
doThatMightThrow();
} catch (e) {
throw e;
}
try {
doThatMightThrow();
} catch (e) {
doBeforeRethrow();
throw e;
}
Disallow Unnecessary Computed Property Keys
Description: Unnecessary usage of Computed Property Keys should be disallowed in objects and classes.
let alpha = { ['0']: 0 };
let beta = { 'a': 0 };
Disallow Unnecessary Concatenation of Strings
Description: This rule aims to flag the concatenation of 2 literals when they could be combined into a single literal.
let a = '1' + '0';
let a = "10";
Disallow Unnecessary Constructor
Description: This rule flags class constructors that can be safely removed without changing how the class works.
class A {
constructor () {
}
}
class A { }
Disallow Unnecessary Escape Usage
Description: Escapes that can be safely removed without changing behavior are flagged.
/[a-z-]\:/;
/[a-z-]:/;
Disallow Renaming to Same Name
Description: Renaming of import, export, and destructured assignments to the same name is disallowed
import { alpha as alpha } from "beta";
import * as aplha from "beta";
Disallow Redundant return Statements
Description: A return statement with nothing after it is redundant, and has no effect on the runtime behavior of a function.
function alpha() { return; }
function alpha() { return 5; }
Require let or const Instead of var
Description: let or const should be used instead of var.
var alpha = 'a';
let alpha = 'a';
Disallow use of the void operator.
Description: Void operator should be avoided
let alpha = void beta();
Disallow Warning Comments
Description: Comments that include any of the predefined terms specified in its configuration are reported.
// TODO
// NOT READY FOR PRIME TIME
Disallow Whitespace Before Properties
Description: Whitespaces must be disallowed before properties
alpha [beta]
alpha.beta
Disallow with Statements
Description: The with statement is potentially problematic, so it is better to disallow its use
with (alpha) {
result = Math.sqrt(a * b + b * a);
}
const result = ({x, y}) => Math.sqrt(x * x + y * y);
Enforce the Location of single-line Statements
Description: There should be used a a consistent location for single-line statements.
if (alpha)
beta();
if (alpha) beta();
Enforce Consistent Line Breaks Inside Braces
Description: A number of style guides require line breaks inside of object braces and other tokens.
let alpha = {beta: 1};
let alpha = {
beta: 1
};
Enforce Consistent Spacing Inside Braces
Description: There should be used consistent spacing inside braces.
let dummy = { 'alpha': 'beta' };
let dummy = {'alpha': 'beta'};
Enforce Placing Object Properties on Separate Lines
Description: The object properties must be placed on separate lines.
const dummy = { alpha: "a", beta: "b" };
const dummy = {
alpha: "a",
beta: "b",
};
Require Object Literal Shorthand Syntax
Description: This rule requires method and property shorthand syntax for object literals.
let alpha = {
"beta"() {}
};
let alpha = {
"beta": function() {},
"gamma": c
};
Require Newlines Around Variable Declarations
Description: It is required to add newlines around variable declarations
let alpha, beta, c = 0;
let alpha,
beta,
c = 0;
Enforce Declaration of Variables in Functions
Description: Variables should be declared either together or separately per function ( for var) or block (for let and const) scope.
function dummy() {
let alpha;
let beta;
let gamma;
let delta;
}
Require Assignment Operator Shorthand
Description: It is required to assign operator shorthand where possible.
alpha = alpha + beta;
alpha += beta;
Enforce Consistent Linebreak Style for Operators
Description: There should be a consistent linebreak style for operators.
alpha = 1
+
2;
alpha = 1 + 2;
Require Padding Within Blocks
Description: Consistent empty line padding within blocks is enforced.
if (alpha) {
beta();
}
if (alpha) {
beta();
}
Require Padding Lines Between Statements
Description: It is required to pad lines between statements.
function alpha() {
beta();
return;
}
function alpha() {
beta();
return;
}
Require Using Arrow Functions for Callbacks
Description: It is required to use aarow functions for callbacks.
foo(function(alpha) { return alpha; });
foo(alpha => alpha);
Suggest Using const
Description: If a variable is never reassigned, using the const declaration is better.
let alpha = 3;
console.log(alpha);
const alpha = 0;
Prefer Destructuring from Arrays and Objects
Description: It is required to destructure from arrays and/or objects.
let alpha = array[0];
let [ alpha ] = array;
Disallow Use of Math.pow in Favor of **
Description: It is suggested to avoid Math.pow and use the ** operator instead.
const alpha = Math.pow(2, 8);
const alpha = 2 ** 8;
Use Named Capture Group
Description: It is suggested to use named capture group in regular expression.
const alpha = /(ca[rt])/;
const alpha = /(?<id>ca[rt])/;
Disallow parseInt
Description: This rule disallows parseInt() if it is called with two arguments: a string and a radix option of binary, octal, or hexadecimal.
parseInt("111110111", 2) === 503;
0b111110111 === 503;
Prefer Use Object Spread over Object.assign
Description: It is prefered to use an object spread over Object.assign.
Object.assign({}, alpha)
Object.assign(...alpha);
Require Using Error as Promise Rejection Reasons
Description: It is considered good practice to only pass instances of the built-in Error object to the reject() function for user-defined errors in Promises.
Promise.reject("something bad happened");
Promise.reject(new Error("something bad happened"));
Suggest Using Reflect Methods
Description: Using Reflect methods where applicable is prefered.
alpha.apply(undefined, args);
Reflect.apply(alpha, undefined, args);
Disallow Use of the RegExp
Constructor
Description: The use of the RegExp constructor function with string literals as its arguments should be disallowed.
new RegExp("abc");
/abc/;
Suggest Using the Rest Parameters
Description: The usage of arguments variables is flagged.
function alpha() {
console.log(unknown);
}
function alpha(...args) {
console.log(args);
}
Suggest Using Spread Syntax
Description: Using spread syntax instead of .apply() is suggested.
alpha.apply(undefined, args);
alpha(...args);
Suggest Using Template Literals
Description: Flag usage of + operators with strings should be avoided.
let str = "Hello, " + name + "!";
let str = `Hello, ${name}!`
Require Quotes Around Object Keys
Description: Quotes around object literal property names are required.
let object = {
alpha: "dummy",
beta: 42
};
let object = {
"alpha": "dummy",
"beta": 42
};
Enforce the Consistent Use of quotes
Description: There should be kept a consistent use of either backticks, double, or single quotes.
let single = 'single';
let double = "double";
Require Radix Parameter
Description: The unintended conversion of a string to a number of a different base than intended or at preventing the redundant 10 radix if targeting modern environments only is prevented.
let num = parseInt("071");
let num = parseInt("071", 10);
Disallow Assignments Leading to Race Conditions
Description: This rule aims to report assignments to variables or properties in cases where the assignments may be based on outdated values.
let alpha;
async function beta() {
result += await dummy;
}
Disallow async Functions with no await
Description: async functions which have no await expression create a warning.
async function alpha() {
do();
}
async function alpha() {
await do();
}
Require JSDoc Comments
Description: JSDoc comments for specified nodes are required.
function foo() {
return 10;
}
/**
* It returns 10
*/
function alpha() {
return 10;
}
Enforce the use of u
flag on RegExp
Description: This rule aims to enforce the use of u flag on regular expressions.
const a = /aaa/
const a = /aaa/u
Disallow Generator Functions with no yield
Description: Warnings for generator functions that do not have the yield keyword are generated.
function* alpha() {
return 10;
}
function* alpha() {
yield 5;
return 10;
}
Enforce Spacing Between Rest and Spread Operators
Description: Terminators around semicolons should be avoided.
[... alpha, 4, 5, 6];
let [alpha, beta, ... theta] = [1, 2, 3, 4, 5];
[...alpha, 4, 5, 6];
let [alpha, beta, ...theta] = [1, 2, 3, 4, 5];
Enforce spacing before and after semicolons
Description: JavaScript allows you to place unnecessary spaces before or after a semicolon.
Enforce location of semicolons
Description: Generally, semicolons are at the end of lines. However, in semicolon-less style, semicolons are at the beginning of lines. This rule enforces that semicolons are at the configured location.
Require Semicolons Instead of ASI
Description: There should be a consistent use of semicolons.
let value = 5
let value = 5;
Import Sorting
Description: This rule checks all import declarations and verifies that all imports are first sorted by the used member syntax and then alphabetically by the first member or alias name.
import a from 'alpha.js';
import A from 'test.js';
import b from 'beta.js'
import a from 'alpha.js';
import b from 'beta.js';
import A from 'test.js';
Require Object Keys to be Sorted
Description: This rule checks all property definitions of object expressions and verifies that all variables are sorted alphabetically.
let obj = {a: 1, c: 3, b: 2};
let obj = {a: 1, b: 2, c: 3};
Variable Sorting
Description: This rule checks all variable declaration blocks and verifies that all variables are sorted alphabetically.
let b, a;
let a, b, c, d;
Require Space Before Blocks
Description: There should be consistency of spacing before blocks. It is only applied on blocks that don't begin on a new line.
if (alpha){
beta();
}
if (alpha) {
beta();
}
Require a Space Before Function Parenthesis
Description: There should be consistent spacing before function parentheses and as such, will warn whenever whitespace doesn't match the preferences specified.
function alpha() {
// ...
}
function alpha () {
// ...
}
Disallow or enforce spaces inside of parentheses
Description: Spaces inside of parentheses should be disallowed.
dummy();
dummy( );
Require Spacing Around Infix Operators
Description: This rule is aimed at ensuring there are spaces around infix operators.
alpha+beta
alpha + beta
Require Spaces Before/After Unary Operators
Description: Ther should be consistency regarding the spaces after words unary operators and after/before nonwords unary operators.
typeof!alpha;
typeof !alpha;
Requires Whitespace
Description: There should be consistency of spacing after the start of a comment // or /*. It also provides several exceptions for various documentation styles.
//This is a comment without a whitespace at the beginning
// This is a comment with a whitespace at the beginning
Require Strict Mode Directives
Description: Strict mode directives are required.
function alpha() {
}
"use strict";
function alpha() {
}
Enforce Spacing in Switch Statements
Description: Spacing around colons of switch statements is required.
switch (alpha) {
case 0 :break;
default :beta();
}
switch (alpha) {
case 0: beta(); break;
case 1:
test();
break;
default:
dummy();
break;
}
Require Symbol Description
Description: A description when creating symbols is required.
let alpha = Symbol();
let alpha = Symbol("description");
Enforce Usage of Spacing in Template Strings
Description: There should be consistency around the spacing inside of template literals.
`dummy, ${data.test}`
`hello, ${ data.test }`
Require Spacing Between Tags and Literals
Description: There should be consistency around the spacing between template tag functions and their template literals.
func`Dummy`;
func `Dummy`;
Require Unicode BOM
Description: This rules requires the Unicode Byte Order Mark (BOM).
let abc;
U+FEFF
let abc;
Require Calls to isNaN
Description: Comparisons to 'NaN' should be avoided.
if (alpha == NaN) {
// ...
}
if (isNaN(alpha)) {
// ...
}
Enforce Valid JSDoc Comments
Description: There should be used valid and consistent JSDoc comments.
/**
* Add two numbers.
* @param {number} num The first number.
* @returns The sum of the two numbers.
*/
/**
* Add two numbers.
* @param {number} num1 The first number.
* @param {number} num2 The second number.
* @returns {number} The sum of the two numbers.
*/
Enforce Comparing typeof
Description: typeof expressions must be compared to valid string literals.
typeof alpha === "strnig"
typeof alpha === "string"
Require Variable Declarations at Top
Description: All variable declarations shold be in the leading series of statements.
function dog() {
for (let i=0; i<10; i++) {}
}
function do() {
let i;
for (i=0; i<10; i++) {}
}
Require IIFEs to be Wrapped
Description: All immediately-invoked function expressions are required to be wrapped in parentheses.
let alpha = function () { return { beta: 1 };}();
let alpha = (function () { return { beta: 1 };}());
Require Regex Literals to be Wrapped
Description: regex literals are required to be wrapped.
function alpha() {
return /ball/.test("beta");
}
function alpha() {
return (/ball/).test("beta");
}
Enforce Spacing Around the *
Description: This rule enforces spacing around the * in yield expressions.
function*generator() {
yield*other();
}
function* generator() {
yield* other();
}
Require or disallow Yoda Conditions
Description: This rule aims to enforce consistent style of conditions which compare a variable to a literal value.
if ("blue" === color) {
// ...
}
if (value === "blue") {
// ...
}
Detect Inline Styles in Components
Description: This rule detects inline style objects when they contain literal values.
const Hello = React.createClass({
render: function() {
return <Text style={{backgroundColor: '#FFF'}}>Hello {this.props.name}</Text>;
}
});
const Hello = React.createClass({
render: function() {
return <Text style={styles.name}>Hello {this.props.name}</Text>;
}
});
Avoid Single Element Style Arrays
Description: Using single element style arrays cause unnecessary re-renders as each time the array's identity changes.
<View style={[{width: 10}]} />
<View style={{width: 10}} />