@odg/eslint-config-odg-linter-js v0.8.0
Standard Code
- Introduction
- File Name Convention
- Semi Rule
- Quotes Rule
- Indent Rule
- Line Break Rule
- EOL last Rule
- Max Line Len Rule
- CamelCase Rule
- Padded Block Rule
- Lines Between Class Members
- No Multi Assign Rule
- Explicit Member Accessibility Rule
- Default Param Last Rule
- Space Before Function Paren
- Exception Handled
- Array Space
- Key Word Space
- Space Format
- UTF-8 Only
- No Space in Parentheses
- No Multiple Space
- Useless String Concat
- No Self Assign
- Force Return Type
- Array Bracket Line
- Unused Vars
- Comma Spacing
- Comma Dangle
- Prefer Arrow Function
- Prefer Destructuring
- Arrow Function Body
- Arrow Function Parentheses
- No Empty Block
- No Long Syntax
- Useless Call Code
- Useless Catch Code
- Useless Expression Code
- Useless Return Code
- Useless Construct Code
- Useless Parens
- Useless Boolean
- Useless Alias
- Return New line
- Comment Multi Line Prefer
- No throw Literal
- No Unreachable
- No Multiline String
- No Unsafe Assign
- Disallow Script Url
- Disallow Undefined
- Function Name
- Function Style
- No Else Return
- No Console Spaces
- No Hex Escape
- Prefer Array Flat Map
- Prefer String Slice
- Prefer Modern DOM
- Prefer Prefix Number
- Numeric Separators Style
- Prefer Default Parame
- No Avoid Reverse
- Prefer Code Point
- Bool Param Default
- Class Name Convention
- Comma Or Logical Or Case
- No Constructor Bind
- No Thenable
- No Unreadable Iife
- Prefer Native Cast
- Prefer Logical Operator Over Ternary
- Prefer Event Target
- Prefer Object From Entries
- Prefer Array From.Map
- Prefer Array Flat
- This Pattern
- Use Dot
- Use this
- Use IsNan
- Dot Object Format
- No Trailing Space
- Type Format
- Max Statements Per Line
- No Constant Condition
- No Debugger
- Not Duplicate Case
- Regex Block
- No Overwrite Exception
- No Extra Semi
- No Function Overwrite
- No Delete Var
- No Lone Blocks
- No Proto
- No Useless Computed Key
- No Declare in Block
- No Nonoctal Decimal Escape
- No Import Absolute Path
- No Webpack Loader Syntax
- No Magic Number
- Security Negation
- Regex Space
- Array No Space
- Valid TypeOf
- Strict equality
- No Label
- Full Decimal Number
- No Global Overwrite
- Not Used New
- No New Function
- No Redeclare
- No Self Compare
- Loop Valid
- Useless Scape
- No Yoda
- No Undefined declare
- No New require
- No New Object
- No New Symbol
- Var Size
- Max Depth
- Max Params
- Max Statements
- Operator Assignment
- Require Yield
- Prefer Rest Params
- Symbol Description
- No Await Return
- Max Class Per File
- No Constructor Return
- Prefer Exponentiation Operator
- Prefer Object Spread
- Accessor Pairs
- Default Case Last
- Prefer Literals
- Useless Condition
- No Multiple Empty Line
- No Misused New
- No Semicolon Before spacing
- Disallow Type
- Disallow Empty Function
- Disallow Duplicate Imports
- Disallow Unnecessary Type
- Disallow Caller
- Disallow Underscore
- Disallow Param Reassign
- Prefer Const
- Array Type
- Disallow Await sync function
- Method Signature Style
- No Unnecessary Type Assertion
- No Unsafe Call
- No Var
- Operator BreakLine
- Generator Function Stars
- No Unsafe Optional Chaining
- Array Callback
- Space Types
- Curly
- Quote Props
- Brace Style
- Comma Style
- Object BreakLine
- No Shadow
- Promise Rules
- Import
- Documentation
- Regex Rules
- No Optional With Assertion
- No Control Character
- No Dupe Condition
- No Empty Alternative
- No Empty Capturing Group
- No Empty Character Class
- No Empty Group
- No Empty Look Rounds Assertion
- No Escape Backspace
- No Invalid Regexp
- No Lazy Ends
- No Misleading Unicode Character
- No Optional Assertion
- No Potentially Useless BackReference
- No Useless Assertions
- No Useless BackReference
- No Useless Dollar Replacements
- strict
- Confusing Quantifier
- Control Character Escape
- Negation
- No Dupe Characters Character Class
- No Invisible Character
- No Legacy Features
- No Non Standard Flag
- No Obscure Range
- No Trivially Nested Quantifier
- No Unused Capturing Group
- No Useless Character Class
- No Useless Flag
- No Useless Lazy
- No Useless Quantifier
- No Useless Range
- No Useless Two Num Quantifier
- No Zero Quantifier
- Optimal LookAround Quantifier
- Optimal Quantifier Concatenation
- Prefer Quantifier
- Prefer Range
- Sort Alternatives
- Hexadecimal Escape
- Match Any
- No Useless Escape
- No Useless Non Capturing Group
- Prefer Character Class
- Prefer D
- Prefer Plus
- Prefer Question Quantifier
- Prefer Star Quantifier
- Prefer Unicode Code Point Escapes
- Prefer W
- Sort Character Class Elements
- Sort Flags
- Prefer Named Capture Group
- Security
- Eval Disabled
- Detect Unsafe Regex
- Buffer No Assert
- No Exec Child Process
- No Mustache Scape
- No Csrf Before Method Override
- No Literal Fs Filename
- No Pseudo Random Bytes
- Prevent Secret Token
- Prevent Literal Code
- No Import Dynamic
- Security SSL
- Security Encrypt/Access
- Certificate Transparency
- No Log confidential information
- Content Length
- Anti Trojan Source No Bidi
- Cookie Httponly
- Protect XSS Render
- Force Integrity
- DNS prefetching
- Catch Error Name
- Consistent Destructured
- Consistent Function Scope
- Exception With Message
- Escape Case
- New For Builtin
- No Abusive Eslint Disable
- Prefer for-of
- No Array Push Push
- No Await Chased
- No Document Cookie
- No Empty File
- No Instance Of Array
- No Invalid Remove Event Listener
- No Lonely If
- No Nested Ternary
- No New Buffer
- No This Assignment
- No Useless Fallback In Spread
- No Useless Length Check
- No Useless Spread
- No Useless Switch Case
- No Useless Undefined
- Prefer Add Event Listener
- Prefer Array Find
- Prefer Array Index Of
- Prefer Array Some
- Prefer Dom Node Append
- Prefer Include
- Prefer Keyboard Event Key
- Prefer Negative Index
- Prefer Optional Catch Binding
- Prefer Prototype Methods
- Prefer Query Selector
- Prefer Regexp Test
- Prefer Spread
- Prefer String Replace All
- Prefer String Starts Ends With
- Prefer String Trim Start End
- Prefer Switch
- Prefer Ternary
- Prevent Abbreviations
- Consistent Relative URL
- Require Array Join Separator
- Require Number To Fixed Digits Argument
- Template String Indent
- Performance
- Errors
- Possible Errors
Introduction
Installation
Add dependence to package.json
npm install eslint @odg/eslint-config-odg-linter-js \
eslint-plugin-jsdoc@* eslint-plugin-import@* \
eslint-plugin-promise@* eslint-plugin-regexp@* \
eslint-plugin-filenames@* --save-dev
# or
yarn add -D eslint @odg/eslint-config-odg-linter-js \
eslint-plugin-jsdoc@* eslint-plugin-import@* \
eslint-plugin-promise@* eslint-plugin-regexp@* \
eslint-plugin-filenames@*
Add extends in your .eslintrc
file
{
"extends": [
"@odg/odg-linter-js",
],
"overrides": [
{
"files": [ "*.ts", "*.tsx" ],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": { "jsx": true },
"ecmaVersion": 2018,
"sourceType": "module",
"project": [ "tsconfig.json" ], // Specify it only for TypeScript files
},
},
],
}
Test: npm run eslint
or yarn eslint
File Name Convention
File Name Convention
https://github.com/selaux/eslint-plugin-filenames
π Examples of correct code
// File name Foo.ts
export default class Foo {
}
π Examples of incorrect code
// File name FooClass.ts
export default class Foo {
}
Semi Rule
Requires semicolons at the end of statements
https://eslint.org/docs/rules/semi#semi
π Examples of correct code
var name = "ODG";
object.method = function() {
// ...
};
class Foo {
bar = 1;
}
π Examples of incorrect code
var name = "ODG"
object.method = function() {
// ...
}
class Foo {
bar = 1
}
Quotes Rule
Requires the use of double quotes wherever possible
https://eslint.org/docs/rules/quotes#quotes
π Examples of correct code
var double = "double";
var backtick = `back
tick`; // backticks are allowed due to newline
var backtick = tag`backtick`;
π Examples of incorrect code
var single = 'single';
var unescaped = 'a string containing "double" quotes';
var backtick = `back\ntick`; // you can use \n in single or double quoted strings
Indent Rule
Requires indent with 4 spaces
https://eslint.org/docs/rules/indent#indent https://sonarsource.github.io/rspec/#/rspec/S3973/javascript
π Examples of correct code
if (a) {
b=c;
function foo(d) {
e=f;
}
}
π Examples of incorrect code
if (a) {
b=c;
function foo(d) {
e=f;
}
}
Line Break Rule
Enforces the usage of Unix line endings: \n
for LF.
https://eslint.org/docs/rules/linebreak-style#linebreak-style
π Examples of correct code
var a = 'a'; // \n
π Examples of incorrect code
var a = 'a'; // \r\n
EOL last Rule
Force empty end line
https://eslint.org/docs/rules/eol-last#eol-last
π Examples of correct code
function doSmth() {
var foo = 2;
} // \n
π Examples of incorrect code
function doSmth() {
var foo = 2;
}
Max Line Len Rule
Max line len is 120
https://eslint.org/docs/rules/max-len#max-len
π Examples of correct code
var foo = {
"bar": "This is a bar.",
"baz": { "qux": "This is a qux" },
"difficult": "to read",
};
π Examples of incorrect code
var foo = { "bar": "This is a bar.", "baz": { "qux": "This is a qux" }, "difficult": "to read" };
CamelCase Rule
Force use camelcase variable
https://eslint.org/docs/rules/camelcase#camelcase
π Examples of correct code
import { no_camelcased as camelCased } from "external-module";
var myFavoriteColor = "#112C85";
var _myFavoriteColor = "#112C85";
var myFavoriteColor_ = "#112C85";
var MY_FAVORITE_COLOR = "#112C85";
π Examples of incorrect code
import { no_camelcased } from "external-module"
var my_favorite_color = "#112C85";
function do_something() {
// ...
}
Padded Block Rule
force empty line in blocks
https://eslint.org/docs/rules/padded-blocks#padded-blocks
{
"classes": "always",
"blocks": "never",
"switches": "never",
}
π Examples of correct code
class ClassName {
variable = 1;
}
switch (a) {
case 0: foo();
}
if (a) {
a = b;
}
π Examples of incorrect code
class ClassName {
variable = 1;
}
class ClassName {
variable = 1;
}
switch (a) {
case 0: foo();
}
if (a) {
a = b;
}
Lines Between Class Members
Enforces consistent spacing before function parenthesis.
https://eslint.org/docs/rules/lines-between-class-members#lines-between-class-members
π Examples of correct code
class MyClass {
x;
foo() {
//...
}
bar() {
//...
}
}
π Examples of incorrect code
class MyClass {
x;
foo() {
//...
}
bar() {
//...
}
}
No Multi Assign Rule
Chaining the assignment of variables can lead to unexpected results and be difficult to read. Disabled.
https://eslint.org/docs/rules/no-multi-assign#no-multi-assign
π Examples of correct code
var a = 5;
var b = 5;
var c = 5;
const foo = "baz";
const bar = "baz";
let a = c;
let b = c;
class Foo {
a = 10;
b = 10;
}
a = "quux";
b = "quux";
π Examples of incorrect code
var a = b = c = 5;
const foo = bar = "baz";
let a =
b =
c;
class Foo {
a = b = 10;
}
a = b = "quux";
Explicit Member Accessibility Rule
Force specific public/private or protected visibility
{
"anonymous": "never",
"named": "never",
"asyncArrow": "always"
}
π Examples of correct code
class ClassName {
public a = 1;
protected c = 2;
private b = 3;
}
π Examples of incorrect code
class ClassName {
a = 1;
c = 2;
b = 3;
}
Default Param Last Rule
Enforces default parameters to be last.
https://eslint.org/docs/rules/default-param-last#default-param-last
π Examples of correct code
function f(a = 0) {}
function f(a: number, b = 0) {}
function f(a: number, b?: number) {}
function f(a: number, b?: number, c = 0) {}
function f(a: number, b = 0, c?: number) {}
class Foo {
constructor(public a, private b = 0) {}
}
class Foo {
constructor(public a, private b?: number) {}
}
π Examples of incorrect code
function f(a = 0, b: number) {}
function f(a: number, b = 0, c: number) {}
function f(a: number, b?: number, c: number) {}
class Foo {
constructor(public a = 10, private b: number) {}
}
class Foo {
constructor(public a?: number, private b: number) {}
}
Space Before Function Paren
Enforces default parameters to be last.
π Examples of correct code
foo(function() {
})
function foo() {
}
(async () => {})()
π Examples of incorrect code
foo(function () {
})
function foo () {
}
(async() => {})()
Exception Handled
Enforces callback error handling.
https://eslint.org/docs/rules/handle-callback-err https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/handle-callback-err.md
π Examples of correct code
function loadData (err, data) {
if (err) {
console.log(err.stack);
}
doSomething();
}
function loadData (exception, data) {
if (exception) {
console.log(exception);
}
doSomething();
}
function generateError (err) {
if (err) {
throw new Exception(err.message);
}
}
π Examples of incorrect code
function loadData (err, data) {
doSomething();
}
function loadData (exception, data) {
doSomething();
}
Class Name
This rule requires constructor names to begin with a capital letter.
https://eslint.org/docs/rules/new-cap
π Examples of correct code
var friend = new Person();
π Examples of incorrect code
var friend = new person();
var friend = Person();
Array Space
requires one or more spaces or newlines inside array brackets, and disallow space inside of computed properties.
https://eslint.org/docs/rules/array-bracket-spacing#array-bracket-spacing
https://eslint.org/docs/rules/computed-property-spacing#computed-property-spacing
π Examples of correct code
var arr = [ 'foo', 'bar' ];
var [ x, y ] = z;
var c = arr[0];
π Examples of incorrect code
var arr = ['foo', 'bar'];
var [x,y] = z;
var c = arr[ 0 ];
var c = object[ "foo" ];
var c = object["foo" ];
var c = object[ "foo"];
Key Word Space
Enforces consistent spacing before and after keywords.
https://eslint.org/docs/rules/keyword-spacing#keyword-spacing
π Examples of correct code
if (foo) {
//...
} else if (bar) {
//...
} else {
//...
}
try {
} catch(e) {
// code ...
}
π Examples of incorrect code
if(foo){
//...
}else if(bar){
//...
}else{
//...
}
try{
}catch(e){
// code ...
}
Space Format
This rule enforces consistency regarding the spaces after
https://eslint.org/docs/rules/space-unary-ops#space-unary-ops
π Examples of correct code
a++;
++a;
--a;
a--;
async function foo() {
await bar;
}
if (!foo) {
}
const value = +"3";
π Examples of incorrect code
a ++;
++ a;
-- a;
a --;
async function foo() {
await(bar);
}
if (! foo) {
}
const value = + "3";
UTF-8 Only
Disallow the Unicode Byte Order Mark (BOM).
https://eslint.org/docs/rules/unicode-bom#unicode-bom
No Space in Parentheses
Disallows or enforce spaces inside of parentheses.
https://eslint.org/docs/rules/space-in-parens#space-in-parens
π Examples of correct code
foo();
foo('bar');
foo(/* bar */);
var foo = (1 + 2) * 3;
(function () { return 'bar'; }());
π Examples of incorrect code
foo( );
foo( 'bar');
foo('bar' );
foo( 'bar' );
foo( /* bar */ );
var foo = ( 1 + 2 ) * 3;
( function () { return 'bar'; }() );
No Multiple Space
Disallows multiple consecutive spaces.
https://eslint.org/docs/rules/no-multi-spaces#no-multi-spaces
π Examples of correct code
var a = 1;
if(foo === "bar") {}
a << b
var arr = [ 1, 2 ];
var a = [];
var baz = [];
a ? b : c
π Examples of incorrect code
var a = 1;
if(foo === "bar") {}
a << b
var arr = [1, 2];
var c = [];
var baz = [];
a ? b : c
Useless String Concat
Disallows useless string concat.
https://eslint.org/docs/rules/no-useless-concat#no-useless-concat
π Examples of correct code
var c = a + b;
var c = '1' + a;
var a = 1 + '1';
var c = 1 - 2;
// when the string concatenation is multiline
var c = "foo" +
"bar";
π Examples of incorrect code
var a = `some` + `string`;
// these are the same as "10"
var a = '1' + '0';
var a = '1' + `0`;
var a = `1` + '0';
var a = `1` + `0`;
No Self Assign
Disallows assignments where both sides are exactly the same.
https://eslint.org/docs/rules/no-self-assign#no-self-assign
π Examples of correct code
foo = bar;
[a, b] = [b, a];
// This pattern is warned by the `no-use-before-define` rule.
let foo = foo;
// The default values have an effect.
[foo = 1] = [foo];
// non-self-assignments with properties.
obj.a = obj.b;
obj.a.b = obj.c.b;
obj.a.b = obj.a.c;
obj[a] = obj["a"];
π Examples of incorrect code
foo = foo;
[a, b] = [a, b];
[a, ...b] = [x, ...b];
({a, b} = {a, x});
foo &&= foo;
foo ||= foo;
foo ??= foo;
Force Return Type
Force fill return type in typescript
π Examples of correct code
function test(): void {
return;
}
// A return value of type number
var fn = function (): number {
return 1;
};
// A return value of type string
var arrowFn = (): string => 'test';
class Test {
// No return value should be expected (void)
method(): void {
return;
}
}
π Examples of incorrect code
function test() {
return;
}
// Should indicate that a number is returned
var fn = function () {
return 1;
};
// Should indicate that a string is returned
var arrowFn = () => 'test';
class Test {
// Should indicate that no value is returned (void)
method() {
return;
}
}
Array Bracket Line
Requires consistent usage of linebreaks for each pair of brackets. It reports an error if one bracket in the pair has a linebreak inside it and the other bracket does not.
https://eslint.org/docs/rules/array-bracket-newline#consistent
π Examples of correct code
var a = [];
var c = [ 1 ];
var d = [
1
];
var f = [
function foo() {
dosomething();
}
];
π Examples of incorrect code
var a = [1
];
var b = [
1];
var c = [function foo() {
dosomething();
}
]
var d = [
function foo() {
dosomething();
}]
Unused Vars
Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers.
https://eslint.org/docs/rules/no-unused-vars#no-unused-vars
π Examples of correct code
var x = 10;
alert(x);
// foo is considered used here
myFunc(function foo() {
// ...
}.bind(this));
(function(foo) {
return foo;
})();
var myFunc;
myFunc = setTimeout(function() {
// myFunc is considered used
myFunc();
}, 50);
// Only the second argument from the destructured array is used.
function getY([, y]) {
return y;
}
π Examples of incorrect code
// It checks variables you have defined as global
some_unused_var = 42;
var x;
// Write-only variables are not considered as used.
var y = 10;
y = 5;
// A read for a modification of itself is not considered as used.
var z = 0;
z = z + 1;
// By default, unused arguments cause warnings.
(function(foo) {
return 5;
})();
// Unused recursive functions also cause warnings.
function fact(n) {
if (n < 2) return 1;
return n * fact(n - 1);
}
// When a function definition destructures an array, unused entries from the array also cause warnings.
function getY([x, y]) {
return y;
}
Comma Spacing
Putting default parameter at last allows function calls to omit optional tail arguments.
https://eslint.org/docs/rules/comma-spacing#options
π Examples of correct code
var foo = 1, bar = 2
, baz = 3;
var arr = [1, 2];
var arr = [1,, 3]
var obj = {"foo": "bar", "baz": "qur"};
foo(a, b);
new Foo(a, b);
function foo(a, b){}
a, b
π Examples of incorrect code
var foo = 1 ,bar = 2;
var arr = [1 , 2];
var obj = {"foo": "bar" ,"baz": "qur"};
foo(a ,b);
new Foo(a ,b);
function foo(a ,b){}
a ,b
Comma Dangle
This rule enforces consistent use of trailing commas in object and array literals.
https://eslint.org/docs/rules/comma-dangle#comma-dangle https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/comma-dangle.md
π Examples of correct code
var foo = {
bar: "baz",
qux: "quux",
bar: "baz",
};
function baz(
a,
b,
c,
) {
// code ...
}
π Examples of incorrect code
var foo = {
bar: "baz",
qux: "quux",
bar: "baz"
};
function baz(
a,
b,
c
) {
// code ...
}
Prefer Arrow Function
Requires using arrow functions for callbacks.
https://eslint.org/docs/rules/prefer-arrow-callback#prefer-arrow-callback
π Examples of correct code
foo(a => a);
foo(() => this.a);
foo(function*() { yield; });
π Examples of incorrect code
foo(function(a) { return a; });
foo(function() { return this.a; }.bind(this));
Prefer Destructuring
Require destructuring from arrays and/or objects
https://eslint.org/docs/latest/rules/prefer-destructuring
π Examples of correct code
var [ foo ] = array;
var foo = array[someIndex];
var { foo } = object;
var foo = object.bar;
let foo;
({ foo } = object);
π Examples of incorrect code
// With `array` enabled
var foo = array[0];
// With `object` enabled
var foo = object.foo;
var foo = object['foo'];
Arrow Function Body
Enforces no braces where they can be omitted
https://eslint.org/docs/rules/arrow-body-style#arrow-body-style
π Examples of correct code
() => {};
(a) => {};
(a) => a;
(a) => {'\n'}
a.then((foo) => {});
a.then((foo) => { if (true) {} });
π Examples of incorrect code
a => {};
a => a;
a => {'\n'};
a.then(foo => {});
a.then(foo => a);
a(foo => { if (true) {} });
Arrow Function Parentheses
Enforces parentheses around arguments in all cases.
https://eslint.org/docs/rules/arrow-parens
π Examples of correct code
let foo = () => 0;
let foo = (retv, name) => {
retv[name] = true;
return retv;
};
let foo = () => ({
bar: {
foo: 1,
bar: 2,
}
});
let foo = () => { bar(); };
let foo = () => {};
let foo = () => { /* do nothing */ };
let foo = () => {
// do nothing.
};
let foo = () => ({ bar: 0 });
π Examples of incorrect code
let foo = () => {
return 0;
};
let foo = () => {
return {
bar: {
foo: 1,
bar: 2,
}
};
};
No Empty Block
Disallows empty block statements.
https://eslint.org/docs/rules/no-empty#no-empty
π Examples of correct code
if (!foo) {
// code
}
while (foo) {
// code
}
try {
doSomething();
} catch (ex) {
// continue regardless of error
}
try {
doSomething();
} finally {
/* continue regardless of error */
}
π Examples of incorrect code
if (foo) {
} else {
// code
}
while (foo) {
}
switch(foo) {
}
try {
doSomething();
} catch(ex) {
} finally {
}
No Long Syntax
Disallow Array constructors
https://eslint.org/docs/latest/rules/no-array-constructor
π Examples of correct code
const arr: Array<number> = [ 1, 2, 3 ];
const arr: Array<Foo> = [ x, y, z ];
Array(500);
new Array(someOtherArray.length);
π Examples of incorrect code
const arr = Array(0, 1, 2);
const arr = new Array(0, 1, 2);
Useless Call Code
Disallow useless code
https://eslint.org/docs/rules/no-useless-call#no-useless-call
π Examples of correct code
foo.call(obj, 1, 2, 3);
foo.apply(obj, [1, 2, 3]);
obj.foo.call(null, 1, 2, 3);
obj.foo.apply(null, [1, 2, 3]);
obj.foo.call(otherObj, 1, 2, 3);
obj.foo.apply(otherObj, [1, 2, 3]);
// The argument list is variadic.
// Those are warned by the `prefer-spread` rule.
foo.apply(undefined, args);
foo.apply(null, args);
obj.foo.apply(obj, args);
a[++i].foo.call(a[i], 1, 2, 3);
π Examples of incorrect code
foo.call(undefined, 1, 2, 3);
foo.apply(undefined, [1, 2, 3]);
foo.call(null, 1, 2, 3);
foo.apply(null, [1, 2, 3]);
// These are same as `obj.foo(1, 2, 3);`
obj.foo.call(obj, 1, 2, 3);
obj.foo.apply(obj, [1, 2, 3]);
a[i++].foo.call(a[i++], 1, 2, 3);
Useless Catch Code
Disallow useless code
https://eslint.org/docs/rules/no-useless-catch#no-useless-catch
π Examples of correct code
try {
doSomethingThatMightThrow();
} catch (e) {
doSomethingBeforeRethrow();
throw e;
}
try {
doSomethingThatMightThrow();
} catch (e) {
handleError(e);
}
try {
doSomethingThatMightThrow();
} finally {
cleanUp();
}
π Examples of incorrect code
try {
doSomethingThatMightThrow();
} catch (e) {
throw e;
}
try {
doSomethingThatMightThrow();
} catch (e) {
throw e;
} finally {
cleanUp();
}
Useless Expression Code
Disallow useless code
https://eslint.org/docs/rules/no-unused-expressions
π Examples of correct code
{} // In this context, this is a block statement, not an object literal
{myLabel: someVar} // In this context, this is a block statement with a label and expression, not an object literal
function namedFunctionDeclaration () {}
(function aGenuineIIFE () {}());
f()
a = 0
new C
delete a.b
void a
a ? b() : c();
a ? (b = c) : d();
π Examples of incorrect code
0
if(0) 0
{0}
f(0), {}
a && b()
a, b()
c = a, b;
a() && function namedFunctionInExpressionContext () {f();}
(function anIncompleteIIFE () {});
injectGlobal`body{ color: red; }`
function foo() {
"bar" + 1;
}
class Foo {
static {
"use strict"; // class static blocks do not have directive prologues
}
}
Useless Return Code
Disallow useless code
https://eslint.org/docs/rules/no-useless-return#no-useless-return
π Examples of correct code
function foo() { return 5; }
function foo() {
return doSomething();
}
function foo() {
if (condition) {
bar();
return;
} else {
baz();
}
qux();
}
function foo() {
switch (bar) {
case 1:
doSomething();
return;
default:
doSomethingElse();
}
}
function foo() {
for (const foo of bar) {
return;
}
}
π Examples of incorrect code
function foo() { return; }
function foo() {
doSomething();
return;
}
function foo() {
if (condition) {
bar();
return;
} else {
baz();
}
}
function foo() {
switch (bar) {
case 1:
doSomething();
default:
doSomethingElse();
return;
}
}
Useless Construct Code
Disallow useless code
https://eslint.org/docs/rules/no-useless-constructor#options
π Examples of correct code
class A { }
class A {
constructor () {
doSomething();
}
}
class B extends A {
constructor() {
super('foo');
}
}
class B extends A {
constructor() {
super();
doSomething();
}
}
π Examples of incorrect code
class A {
constructor () {
}
}
class B extends A {
constructor (...args) {
super(...args);
}
}
Useless Parens
Disallows unnecessary parentheses.
https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-extra-parens.md https://eslint.org/docs/rules/no-extra-parens#no-extra-parens
π Examples of correct code
a = (b * c);
(a * b) + c;
for (a in (b, c));
for (a in (b));
for (a of (b));
typeof (a);
(function(){} ? a() : b());
class A {
[(x)] = 1;
}
class B {
x = (y + z);
}
π Examples of incorrect code
a = (b * c);
(a * b) + c;
for (a in (b, c));
for (a in (b));
for (a of (b));
typeof (a);
(function(){} ? a() : b());
class A {
[(x)] = 1;
}
class B {
x = (y + z);
}
Useless Boolean
Disallow useless code
https://eslint.org/docs/rules/no-useless-constructor#options
π Examples of correct code
var foo = !!bar;
var foo = Boolean(bar);
function foo() {
return !!bar;
}
var foo = bar ? !!baz : !!bat;
π Examples of incorrect code
var foo = !!!bar;
var foo = !!bar ? baz : bat;
var foo = Boolean(!!bar);
var foo = new Boolean(!!bar);
if (!!foo) {
// ...
}
if (Boolean(foo)) {
// ...
}
while (!!foo) {
// ...
}
do {
// ...
} while (Boolean(foo));
for ( ;!!foo; ) {
// ...
}
Useless Alias
Disallows renaming import, export, and destructured assignments to the same name.
https://eslint.org/docs/rules/no-useless-rename
π Examples of correct code
import * as foo from "foo";
import { foo } from "bar";
import { foo as bar } from "baz";
import { "foo" as bar } from "baz";
export { foo };
export { foo as bar };
export { foo as bar } from "foo";
let { foo } = bar;
let { foo: bar } = baz;
let { [foo]: foo } = bar;
function foo({ bar }) {}
function foo({ bar: baz }) {}
({ foo }) => {}
({ foo: bar }) => {}
π Examples of incorrect code
import { foo as foo } from "bar";
import { "foo" as foo } from "bar";
export { foo as foo };
export { foo as "foo" };
export { foo as foo } from "bar";
export { "foo" as "foo" } from "bar";
let { foo: foo } = bar;
let { 'foo': foo } = bar;
function foo({ bar: bar }) {}
({ foo: foo }) => {}
Return New line
Force new line before return
https://eslint.org/docs/rules/newline-before-return#newline-before-return
π Examples of correct code
function foo(bar) {
var baz = 'baz';
if (bar()) {
return true;
}
if (!bar) {
bar = baz;
return baz;
}
return bar;
}
π Examples of incorrect code
function foo(bar) {
var baz = 'baz';
if (bar()) {
return true;
}
if (!bar) {
bar = baz;
return bar;
}
return bar;
}
Comment Multi Line Prefer
Prefer Multi-line comment formated
https://eslint.org/docs/rules/newline-before-return#newline-before-return
π Examples of correct code
/*
* this line
* calls foo()
*/
foo();
// single-line comment
π Examples of incorrect code
// this line
// calls foo()
foo();
/* this line
calls foo() */
foo();
/* this comment
* is missing a newline after /*
*/
/*
* this comment
* is missing a newline at the end */
/*
* the star in this line should have a space before it
*/
/*
* the star on the following line should have a space before it
*/
No throw Literal
Create custom class to Throw
https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-throw-literal.md https://eslint.org/docs/rules/prefer-promise-reject-errors#prefer-promise-reject-errors
π Examples of correct code
class CustomError extends Error {
// ...
};
const e = new CustomError("error");
throw e;
throw new CustomError("error");
function err() {
return new CustomError();
}
throw err();
const foo = {
bar: new CustomError();
}
throw foo.bar;
// promises
Promise.reject(new CustomError("something bad happened"));
Promise.reject(new TypeError("something bad happened"));
new Promise(function(resolve, reject) {
reject(new CustomError("something bad happened"));
});
var foo = getUnknownValue();
Promise.reject(foo);
π Examples of incorrect code
throw new Error();
throw 'error';
throw 0;
throw undefined;
throw null;
const err = new Error();
throw 'an ' + err;
const err = new Error();
throw `${err}`;
const err = '';
throw err;
function err() {
return '';
}
throw err();
const foo = {
bar: '',
};
throw foo.bar;
// Promise
Promise.reject("something bad happened");
Promise.reject(5);
Promise.reject();
new Promise(function(resolve, reject) {
reject("something bad happened");
});
new Promise(function(resolve, reject) {
reject();
});
No Unreachable
No Unreachable code
https://eslint.org/docs/rules/no-unreachable
π Examples of correct code
function foo() {
function bar() {
return 1;
}
return bar();
}
function bar() {
var x;
return x;
}
switch (foo) {
case 1:
break;
}
π Examples of incorrect code
function foo() {
return true;
console.log("done");
}
function bar() {
throw new Error("Oops!");
console.log("done");
}
while(value) {
break;
console.log("done");
}
throw new Error("Oops!");
console.log("done");
function baz() {
if (Math.random() < 0.5) {
return;
} else {
throw new Error();
}
console.log("done");
}
for (;;) {}
console.log("done");
No Multiline String
Prevent break line in string
https://eslint.org/docs/rules/no-multi-str#no-multi-str
π Examples of correct code
var x = "some very\nlong text";
var x = "some very " +
"long text";
π Examples of incorrect code
var x = "some very \
long text";
No Unsafe Assign
Disallows assigning any to variables and properties.
π Examples of correct code
const x = 1,
y = 1;
const [x] = [1];
[x] = [1] as [number];
function foo(a = 1) {}
class Foo {
constructor(private a = 1) {}
}
class Foo {
private a = 1;
}
// generic position examples
const x: Set<string> = new Set<string>();
const x: Map<string, string> = new Map<string, string>();
const x: Set<string[]> = new Set<string[]>();
const x: Set<Set<Set<string>>> = new Set<Set<Set<string>>>();
π Examples of incorrect code
const x = 1 as any,
y = 1 as any;
const [x] = 1 as any;
const [x] = [] as any[];
const [x] = [1 as any];
[x] = [1] as [any];
function foo(a = 1 as any) {}
class Foo {
constructor(private a = 1 as any) {}
}
class Foo {
private a = 1 as any;
}
// generic position examples
const x: Set<string> = new Set<any>();
const x: Map<string, string> = new Map<string, any>();
const x: Set<string[]> = new Set<any[]>();
const x: Set<Set<Set<string>>> = new Set<Set<Set<any>>>();
Disallow Script Url
Using javascript: URLs is considered by some as a form of eval.
https://eslint.org/docs/rules/no-script-url
π Examples of correct code
location.href = "#";
π Examples of incorrect code
location.href = "javascript:void(0)";
location.href = `javascript:void(0)`;
Disallow Undefined
Disallows the use of undeclared variables unless mentioned in /*global*/ comments.
https://eslint.org/docs/rules/no-undef
π Examples of correct code
/* global someFunction, a */
var foo = someFunction();
var bar = a + 1;
π Examples of incorrect code
var foo = someFunction();
var bar = a + 1;
Function Name
Requires function expressions to have a name, if the name isn't assigned automatically per the ECMAScript specification.
https://eslint.org/docs/rules/func-names
π Examples of correct code
/* global someFunction, a */
var foo = someFunction();
var bar = a + 1;
π Examples of incorrect code
Foo.prototype.bar = function() {};
(function() {
// ...
}())
export default function() {}
Function Style
Enforce the consistent use of either function declarations or expressions
https://eslint.org/docs/latest/rules/func-style
π Examples of correct code
function foo() {
// ...
}
// Methods (functions assigned to objects) are not checked by this rule
SomeObject.foo = function() {
// ...
};
π Examples of incorrect code
var foo = function() {
// ...
};
var foo = () => {};
No Else Return
Disallow else blocks after return statements in if statements
https://eslint.org/docs/latest/rules/no-else-return
π Examples of correct code
function foo() {
if (x) {
return y;
}
return z;
}
function foo() {
if (x) {
return y;
} else if (z) {
var t = "foo";
} else {
return w;
}
}
function foo() {
if (x) {
if (z) {
return y;
}
} else {
return z;
}
}
function foo() {
if (error) {
return 'It failed';
} else if (loading) {
return "It's still loading";
}
}
π Examples of incorrect code
function foo() {
if (x) {
return y;
} else {
return z;
}
}
function foo() {
if (x) {
return y;
} else if (z) {
return w;
} else {
return t;
}
}
function foo() {
if (x) {
return y;
} else {
var t = "foo";
}
return t;
}
function foo() {
if (error) {
return 'It failed';
} else {
if (loading) {
return "It's still loading";
}
}
}
// Two warnings for nested occurrences
function foo() {
if (x) {
if (y) {
return y;
} else {
return x;
}
} else {
return z;
}
}
No Console Spaces
The console.log() method and similar methods joins the parameters with a space, so adding a leading/trailing space to a parameter, results in two spaces being added.
https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-console-spaces.md
π Examples of correct code
console.log('abc');
console.log('abc', 'def');
console.log('abc ');
console.log(' abc');
console.log('abc ', 'def');
console.log('abc\t', 'def');
console.log('abc\n', 'def');
console.log(`
abc
`);
π Examples of incorrect code
console.log('abc ', 'def');
console.log('abc', ' def');
console.log("abc ", " def");
console.log(`abc `, ` def`);
console.debug('abc ', 'def');
console.info('abc ', 'def');
console.warn('abc ', 'def');
console.error('abc ', 'def');
No Hex Escape
Enforce the use of Unicode escapes instead of hexadecimal escapes
https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-hex-escape.md
π Examples of correct code
const foo = '\u001B';
const foo = `\u001B${bar}`;
π Examples of incorrect code
const foo = '\x1B';
const foo = `\x1B${bar}`;
Prefer Array Flat Map
Prefer .flatMap(β¦) over .map(β¦).flat()
https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-array-flat-map.md
π Examples of correct code
const foo = bar.flatMap(element => unicorn(element));
const foo = bar.map(element => unicorn(element)).flat(2);
const foo = bar.map(element => unicorn(element)).foo().flat();
const foo = bar.flat().map(element => unicorn(element));
π Examples of incorrect code
const foo = bar.map(element => unicorn(element)).flat();
const foo = bar.map(element => unicorn(element)).flat(1);
Prefer String Slice
Prefer String#slice() over String#substr() and String#substring()
String#substr() and String#substring() are the two lesser known legacy ways to slice a string. It's better to use String#slice() as it's a more popular option with clearer behavior that has a consistent Array counterpart.
https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-string-slice.md
π Examples of correct code
foo.slice(beginIndex, endIndex);
π Examples of incorrect code
foo.substr(start, length);
foo.substring(indexStart, indexEnd);
Prefer Modern DOM
Prefer .before() over .insertBefore(), .replaceWith() over .replaceChild(), prefer one of .before(), .after(), .append() or .prepend() over insertAdjacentText() and insertAdjacentElement()
https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-modern-dom-apis.md
π Examples of correct code
foo.replaceWith(bar);
foo.replaceWith('bar');
foo.replaceWith(bar, 'baz'));
foo.before(bar)
foo.before('bar')
foo.before(bar, 'baz')
foo.prepend(bar)
foo.prepend('bar')
foo.prepend(bar, 'baz')
foo.append(bar)
foo.append('bar')
foo.append(bar, 'baz')
foo.after(bar)
foo.after('bar')
foo.after(bar, 'baz')
π Examples of incorrect code
foo.replaceChild(baz, bar);
foo.insertBefore(baz, bar);
foo.insertAdjacentText('position', bar);
foo.insertAdjacentElement('position', bar);
Prefer Prefix Number
Prefer Number static properties over global ones
π Examples of correct code
const foo = Number.parseInt('10', 2);
const foo = Number.parseFloat('10.5');
const foo = Number.isNaN(10);
const foo = Number.isFinite(10);
if (Object.is(foo, Number.NaN)) {}
const isPositiveZero = value => value === 0 && 1 / value === Number.POSITIVE_INFINITY;
const isNegativeZero = value => value === 0 && 1 / value === Number.NEGATIVE_INFINITY;
π Examples of incorrect code
const foo = parseInt('10', 2);
const foo = parseFloat('10.5');
const foo = isNaN(10);
const foo = isFinite(10);
if (Object.is(foo, NaN)) {}
const isPositiveZero = value => value === 0 && 1 / value === Infinity;
const isNegativeZero = value => value === 0 && 1 / value === -Infinity;
const {parseInt} = Number;
const foo = parseInt('10', 2);
Numeric Separators Style
Enforce the style of numeric separators by correctly grouping digits
π Examples of correct code
const foo = 1_234_444;
const foo = 1_234.567_89;
const foo = 0xAB_CD_EF;
const foo = 0b1000_1111;
const foo = 0o10_4421;
const foo = 1_294_287_712n;
π Examples of incorrect code
const foo = 1_23_4444;
const foo = 1_234.56789;
const foo = 0xAB_C_D_EF;
const foo = 0b10_00_1111;
const foo = 0o1_0_44_21;
const foo = 1_294_28771_2n;
Prefer Default Parame
Prefer default parameters over reassignment
π Examples of correct code
function abc(foo = 'bar') {}
function abc(foo) {
const parameter = foo || bar();
}
π Examples of incorrect code
function abc(foo) {
foo = foo || 'bar';
}
function abc(foo) {
const bar = foo || 'bar';
}
No Avoid Reverse
Prefer Array#flat() over legacy techniques to flatten arrays
https://github.com/freaktechnik/eslint-plugin-array-func#avoid-reverse
π Examples of correct code
const string = array.reduceRight((p, c) => p + c, "");
const reverseString = array.reduce((p, c) => p + c, "");
π Examples of incorrect code
const string = array.reverse().reduce((p, c) => p + c, '');
const reverseString = array.reverse().reduceRight((p, c) => p + c, '');
Bool Param Default
Optional boolean parameters should have default value
https://sonarsource.github.io/rspec/#/rspec/S4798/javascript
π Examples of correct code
function countPositiveNumbers(arr: number[], countZero = false) {
// ...
}
function toggleProperty(property: string, value: boolean) {
setProperty(property, value);
}
function togglePropertyToCalculatedValue(property: string) {
setProperty(property, calculateProperty());
}
π Examples of incorrect code
function countPositiveNumbers(arr: number[], countZero?: boolean) { // Noncompliant, default value for 'countZero' should be defined
// ...
}
function toggleProperty(property: string, value?: boolean) { // Noncompliant, a new function should be defined
if (value !== undefined) {
setProperty(property, value);
} else {
setProperty(property, calculateProperty());
}
}
Class Name Convention
Class names should comply with a naming convention
https://sonarsource.github.io/rspec/#/rspec/S101/javascript
π Examples of correct code
// With default provided regular expression /^[A-Z][a-zA-Z0-9]*$/:
class MyClass { }
π Examples of incorrect code
class my_class { }
No Class prototype
Class methods should be used instead of "prototype" assignments
https://sonarsource.github.io/rspec/#/rspec/S3525/javascript
π Examples of correct code
class MyClass {
constructor(initializerArgs = []) {
this._values = [...initializerArgs];
}
doSomething() {
//...
}
}
π Examples of incorrect code
function MyNonClass(initializerArgs = []) {
this._values = [...initializerArgs];
}
MyNonClass.prototype.doSomething = function () { // Noncompliant
// ...
}
Comma Or Logical Or Case
Comma and logical OR operators should not be used in switch cases
https://sonarsource.github.io/rspec/#/rspec/S3616/javascript
π Examples of correct code
switch (a) {
case 1:
case 2:
doTheThing(a);
case 3:
case 4:
doThatThing(a);
case 5:
doTheOtherThing(a);
default:
console.log('Neener, neener!');
}
π Examples of incorrect code
switch (a) {
case 1,2: // Noncompliant; only 2 is ever handled by this case
doTheThing(a);
case 3 || 4: // Noncompliant; only '3' is handled
doThatThing(a);
case 5:
doTheOtherThing(a);
default:
console.log('Neener, neener!'); // this happens when a==1 or a == 4
}
No Constructor Bind
Prefer class properties to equivalent setup steps taken in a class' constructor method.
https://github.com/markalfred/eslint-plugin-no-constructor-bind
π Examples of correct code
class User {
greet = () => 'hello'
}
π Examples of incorrect code
class User {
constructor() {
this.greet = this.greet.bind(this)
}
greet() { return 'Hello' }
}
Prefer Code Point
Prefer String#codePointAt(β¦) over String#charCodeAt(β¦) and String.fromCodePoint(β¦) over String.fromCharCode(β¦)
https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-code-point.md
π Examples of correct code
const unicorn = 'π¦'.codePointAt(0).toString(16);
const unicorn = String.fromCodePoint(0x1f984);
π Examples of incorrect code
const unicorn = 'π¦'.charCodeAt(0).toString(16);
const unicorn = String.fromCharCode(0x1f984);
No Thenable
If an object is defined as "thenable", once it's accidentally used in an await expression, it may cause problems:
https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-thenable.md
π Examples of correct code
export {then as success};
const foo = {
success() {}
};
class Foo {
success() {}
}
const foo = bar.then;
π Examples of incorrect code
export {then};
const foo = {
then() {}
};
const foo = {
get then() {}
};
foo.then = function () {}
class Foo {
then() {}
}
class Foo {
static then() {}
}
No Unreadable Iife
IIFE with parenthesized arrow function body is considered unreadable.
https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/no-unreadable-iife.md
π Examples of correct code
const bar = getBar();
const foo = bar ? bar.baz : baz;
const getBaz = bar => (bar ? bar.baz : baz);
const foo = getBaz(getBar());
const foo = (bar => {
return bar ? bar.baz : baz;
})(getBar());
π Examples of incorrect code
const foo = (bar => (bar ? bar.baz : baz))(getBar());
const foo = ((bar, baz) => ({bar, baz}))(bar, baz);
Prefer Native Cast
Prefer using String, Number, BigInt, Boolean, and Symbol directly
π Examples of correct code
const toBoolean = Boolean;
if (Number(foo) === 1) {}
const hasTruthyValue = array.some(Boolean);
const toStringObject = value => new String(value);
const toObject = value => Object(value);
π Examples of incorrect code
const toBoolean = value => Boolean(value);
function toNumber(value) {
return Number(value);
}
if (toNumber(foo) === 1) {}
const hasTruthyValue = array.some(element => element);
Prefer Logical Operator Over Ternary
Prefer using a logical operator over a ternary
Ideally, most reported cases have an equivalent Logical OR(||) expression. The rule intentionally provides suggestions instead of auto-fixes, because in many cases, the nullish coalescing operator (??) should be preferred.
π Examples of correct code
foo ?? bar;
foo || bar;
foo ? bar : baz;
foo.bar ?? foo.baz
foo?.bar ?? baz
π Examples of incorrect code
foo
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago