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();
}