@odg/eslint-config

1.20.1 • Public • Published

Stanley Imagem
ODG Linter Js By Dragons Gamers

✴️ Code Quality for typescript ✴️!

Repository size Made by ODGodinho GitHub last commit License Stargazers

Standard Code

Introduction

Installation

Add dependence to package.json

npm install eslint @odg/eslint-config
# or
yarn add -D eslint @odg/eslint-config

Add extends in your .eslintrc file

{
    "extends": [ "@odg" ]
}

Add script in your package.json file

{
    "scripts": {
        "lint": "eslint --ext .js,.jsx,.ts,.tsx,.json,.jsonc,.json5,.yml,.yaml,.xml,.txt,.svg,.properties,.gradle,.java,.cpp,.c,.cs,.html,.css,.groovy,.gitignore,.npmignore,.toml,.env,.example,.sample,.ini,.php,.bat,.powershell,.ps1,.sh,.bash,.eslintrc",
    }
}

Test: npm run lint or yarn lint

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 https://eslint.org/docs/rules/semi-style

👍 Examples of correct code

var name = "ODG";

object.method = function() {
    // ...
};

class Foo {
    bar = 1;
}

foo();
[1, 2, 3].forEach(bar);

for (
    var i = 0;
    i < 10;
    ++i
) {
    foo();
}

class C {
    static {
        foo();
    }
}

👎 Examples of incorrect code

var name = "ODG"

object.method = function() {
    // ...
}

class Foo {
    bar = 1
}

foo()
;[1, 2, 3].forEach(bar)

for (
    var i = 0
    ; i < 10
    ; ++i
) {
    foo()
}

class C {
    static {
        foo()
        ;bar()
    }
}

Quotes Rule


Requires the use of double quotes wherever possible

Enforces the use of double quotes for all JSX attribute values that don’t contain a double quote.

https://eslint.org/docs/rules/quotes https://eslint.org/docs/rules/jsx-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 Tabs Disallow

https://eslint.org/docs/rules/indent#indent https://sonarsource.github.io/rspec/#/rspec/S3973/javascript https://eslint.org/docs/latest/rules/no-tabs https://eslint.org/docs/latest/rules/no-mixed-spaces-and-tabs

👍 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" };

Camel Case Rule


Force use camel case 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() {
    // ...
}

Strict


A strict mode directive is a "use strict" literal at the beginning of a script or function body. It enables strict mode semantics.

https://eslint.org/docs/latest/rules/strict

👍 Examples of correct code

"use strict";

function foo() {
}

👎 Examples of incorrect code

function foo() {
}

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

https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/explicit-member-accessibility.md

{
    "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.

https://eslint.org/docs/latest/rules/space-before-function-paren https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/space-before-function-paren.md

👍 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 https://eslint.org/docs/rules/yield-star-spacing

👍 Examples of correct code

if (foo) {
    //...
} else if (bar) {
    //...
} else {
    //...
}

try {

} catch(e) {
    // code ...
}

function *generator() {
  yield *other();
}

👎 Examples of incorrect code

if(foo){
    //...
}else if(bar){
    //...
}else{
    //...
}

try{

}catch(e){
    // code ...
}

function*generator() {
  yield*other();
}

function* generator() {
  yield* other();
}

function * generator() {
  yield * other();
}

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

https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/explicit-function-return-type.md

👍 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 ...
}

Arrow Spacing


This rule normalize style of spacing before/after an arrow function’s arrow(=>).

https://eslint.org/docs/latest/rules/arrow-spacing

👍 Examples of correct code

() => {};
(a) => {};
() => {'\n'};

👎 Examples of incorrect code

()=> {};
() =>{};
(a)=> {};
(a) =>{};
a =>a;
a=> a;
()=> {'\n'};
() =>{'\n'};

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 https://sonarsource.github.io/rspec/#/rspec/S3514/javascript

👍 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,
        }
    };
};

Arrow Function No Break Line


Enforces parentheses around arguments in all cases.

https://eslint.org/docs/rules/arrow-parens

👍 Examples of correct code

(foo) => bar;

(foo) => (bar);

(foo) => bar => baz;

(foo) => (
  bar()
);

// functions with block bodies allowed with this rule using any style
// to enforce a consistent location for this case, see the rule: `brace-style`
(foo) => {
  return bar();
}

(foo) =>
{
  return bar();
}

👎 Examples of incorrect code

(foo) =>
  bar;

(foo) =>
  (bar);

(foo) =>
  bar =>
    baz;

(foo) =>
(
  bar()
);

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 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 https://sonarsource.github.io/rspec/#/rspec/S6079/javascript

👍 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.

https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-unsafe-assignment.md

👍 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 https://sonarsource.github.io/rspec/#/rspec/S100/javascript

👍 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 Name Match


This rule requires function names to match the name of the variable or property to which they are assigned. The rule will ignore property assignments where the property name is a literal that is not a valid identifier in the ECMAScript version specified in your configuration (default ES5).

https://eslint.org/docs/latest/rules/func-name-matching

👍 Examples of correct code

var foo = function foo() {};
var foo = function() {};
var foo = () => {};
foo = function foo() {};

obj.foo = function foo() {};
obj['foo'] = function foo() {};
obj['foo//bar'] = function foo() {};
obj[foo] = function bar() {};

var obj = {foo: function foo() {}};
var obj = {[foo]: function bar() {}};
var obj = {'foo//bar': function foo() {}};
var obj = {foo: function() {}};

obj['x' + 2] = function bar(){};
var [ bar ] = [ function bar(){} ];
({[foo]: function bar() {}})

class C {
    foo = function foo() {};
    baz = function() {};
}

// private names are ignored
class D {
    #foo = function foo() {};
    #bar = function foo() {};
    baz() {
        this.#foo = function foo() {};
        this.#foo = function bar() {};
    }
}

module.exports = function foo(name) {};
module['exports'] = function foo(name) {};

👎 Examples of incorrect code

var foo = function bar() {};
foo = function bar() {};
obj.foo = function bar() {};
obj['foo'] = function bar() {};
var obj = {foo: function bar() {}};
({['foo']: function bar() {}});

class C {
    foo = function bar() {};
}

No Use Future Reserved Words


"future reserved words" should not be used as identifiers Special identifiers should not be bound or assigned

https://sonarsource.github.io/rspec/#/rspec/S2137/javascript

👍 Examples of correct code

var elements = document.getElementsByName("foo"); // Compliant
var someData = { package: true };

result = 17;
++result;
var obj = { set p(arg) { } };
var result;
try { } catch (args) { }
function x(arg) { }
function args() { }
var y = function fun() { };
var f = new Function("args", "return 17;");

👎 Examples of incorrect code

var package = document.getElementsByName("foo"); // Noncompliant
eval = 17; // Noncompliant
arguments++; // Noncompliant
++eval; // Noncompliant
var obj = { set p(arguments) { } }; // Noncompliant
var eval; // Noncompliant
try { } catch (arguments) { } // Noncompliant
function x(eval) { } // Noncompliant
function arguments() { } // Noncompliant
var y = function eval() { }; // Noncompliant
var f = new Function("arguments", "return 17;"); // Noncompliant

No Generator Without Yield


Generators should "yield" something

https://sonarsource.github.io/rspec/#/rspec/S3531/javascript

👍 Examples of correct code

function* myGen(a, b) {
  let answer = 0;
  while (answer < 42) {
    answer += a * b;
    yield answer;
  }
}

👎 Examples of incorrect code

function* myGen(a, b) {  // Noncompliant
  let answer = 0;
  answer += a * b;
}

Inverted Assertion Arguments


Assertion arguments should be passed in the correct order

https://sonarsource.github.io/rspec/#/rspec/S3415/javascript

👍 Examples of correct code

const assert = require('chai').assert;
const expect = require('chai').expect;
const should = require('chai').should();

it("inverts arguments", function() {
    assert.equal(aNumber, 42);
    expect(aNumber).to.equal(42);
    should.fail(aNumber, 42);
});

👎 Examples of incorrect code

const assert = require('chai').assert;
const expect = require('chai').expect;
const should = require('chai').should();

it("inverts arguments", function() {
    assert.equal(42, aNumber); // Noncompliant
    expect(42).to.equal(aNumber); // Noncompliant
    should.fail(42, aNumber);  // Noncompliant
});

Max Union Size


Union types should not have too many elements

https://sonarsource.github.io/rspec/#/rspec/S4622/javascript

👍 Examples of correct code

type MyUnionType = MyType1 | MyType2 | MyType3 | MyType4; // Compliant, "type" statements are ignored
let x: MyUnionType;

function foo(value: string, padding: MyUnionType) {
    // ...
}

👎 Examples of incorrect code

let x: MyType1 | MyType2 | MyType3 | MyType4; // Noncompliant

function foo(p1: string, p2: MyType1 | MyType2 | MyType3 | MyType4) { // Noncompliant
    // ...
}

No Redundant Optional


Optional property declarations should not use both '?' and 'undefined' syntax

https://sonarsource.github.io/rspec/#/rspec/S4782/javascript

👍 Examples of correct code

interface Person {
  name: string;
  address: string | undefined;
  pet?: Animal;
}

👎 Examples of incorrect code

interface Person {
  name: string;
  address? : string | undefined;   // Noncompliant, "?" should be removed
  pet?: Animal | undefined; // Noncompliant, "undefined" should be removed
}

Prefer Type Guard


Type guards should be used

https://sonarsource.github.io/rspec/#/rspec/S4322/javascript

👍 Examples of correct code

function isSomething(x: BaseType) : x is Something {
  return (<Something>x).foo !== undefined;
}

if (isSomething(v)) {
  v.foo();
}

👎 Examples of incorrect code

function isSomething(x: BaseType) : boolean { // Noncompliant
  return (<Something>x).foo !== undefined;
}

if (isSomething(v)) {
  (<Something>v).foo();
}

No Production Debug


Delivering code in production with debug features activated is security-sensitive

https://sonarsource.github.io/rspec/#/rspec/S4507/javascript

👍 Examples of correct code

const express = require('express');
const errorhandler = require('errorhandler');

let app = express();

if (process.env.NODE_ENV === 'development') {  // Compliant
  app.use(errorhandler());  // Compliant
}

👎 Examples of incorrect code

const express = require('express');
const errorhandler = require('errorhandler');

let app = express();
app.use(errorhandler()); // Sensitive

Unused Named Groups


Why use named groups only to never use any of them later on in the code?

This rule raises issues every time named groups are: defined but never called anywhere in the code through their name; defined but called elsewhere in the code by their number instead; referenced while not defined.

https://sonarsource.github.io/rspec/#/rspec/S5860/javascript

👍 Examples of correct code

const date = "01/02";

const datePattern = /(?<month>[0-9]{2})\/(?<year>[0-9]{2})/;
const dateMatched = date.match(datePattern);

if (dateMatched !== null) {
  checkValidity(dateMatched.groups.month, dateMatched.groups.year);
}

// ...

const score = "14:1";

const scorePattern = /(?<player1>[0-9]+):(?<player2>[0-9]+)/;
const scoreMatched = score.match(scorePattern);

if (scoreMatched !== null) {
  checkScore(scoreMatched.groups.player1);
  checkScore(scoreMatched.groups.player2);
}

👎 Examples of incorrect code

const date = "01/02";

const datePattern = /(?<month>[0-9]{2})\/(?<year>[0-9]{2})/;
const dateMatched = date.match(datePattern);

if (dateMatched !== null) {
  checkValidity(dateMatched[1], dateMatched[2]); // Noncompliant - numbers instead of names of groups are used
  checkValidity(dateMatched.groups.day); // Noncompliant - there is no group called "day"
}

// ...

const score = "14:1";

const scorePattern = /(?<player1>[0-9]+):(?<player2>[0-9]+)/; // Noncompliant - named groups are never used
const scoreMatched = score.match(scorePattern);

if (scoreMatched !== null) {
  checkScore(score);
}

Get And Setters


A getter and setter for the same property don’t necessarily have to be defined adjacent to each other.

https://eslint.org/docs/latest/rules/grouped-accessor-pairs

👍 Examples of correct code

var foo = {
    get a() {
        return this.val;
    },
    set a(value) {
        this.val = value;
    },
    b: 1
};

var bar = {
    set b(value) {
        this.val = value;
    },
    get b() {
        return this.val;
    },
    a: 1
}

class Foo {
    set a(value) {
        this.val = value;
    }
    get a() {
        return this.val;
    }
    b(){}
}

const Bar = class {
    static get a() {
        return this.val;
    }
    static set a(value) {
        this.val = value;
    }
}

👎 Examples of incorrect code

var foo = {
    get a() {
        return this.val;
    },
    b: 1,
    set a(value) {
        this.val = value;
    }
};

var bar = {
    set b(value) {
        this.val = value;
    },
    a: 1,
    get b() {
        return this.val;
    }
}

class Foo {
    set a(value) {
        this.val = value;
    }
    b(){}
    get a() {
        return this.val;
    }
}

const Bar = class {
    static get a() {
        return this.val;
    }
    b(){}
    static set a(value) {
        this.val = value;
    }
}

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

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-number-properties.md

👍 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

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/numeric-separators-style.md

👍 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

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-default-parameters.md

👍 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

// Noncompliant, default value for 'countZero' should be defined
function countPositiveNumbers(arr: number[], countZero?: boolean) {
  // ...
}

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

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-native-coercion-functions.md

👍 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.

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-logical-operator-over-ternary.md

👍 Examples of correct code

foo ?? bar;
foo || bar;
foo ? bar : baz;
foo.bar ?? foo.baz
foo?.bar ?? baz

👎 Examples of incorrect code

foo ? foo : bar;
foo.bar ? foo.bar : foo.baz
foo?.bar ? foo.bar : baz
!bar ? foo : bar;

Prefer Event Target


Prefer EventTarget over EventEmitter

While EventEmitter is only available in Node.js, EventTarget is also available in Deno and browsers.

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-event-target.md

👍 Examples of correct code

class Foo extends EventTarget {}

const target = new EventTarget();

👎 Examples of incorrect code

import {EventEmitter} from 'node:event';
class Foo extends EventEmitter {}

const emitter = new EventEmitter();

Prefer Object From Entries


Prefer using Object.fromEntries(…) to transform a list of key-value pairs into an object

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-object-from-entries.md

👍 Examples of correct code

const object = Object.fromEntries(pairs);

const object = new Map(pairs);

👎 Examples of incorrect code

const object = pairs.reduce(
    (object, [key, value]) => ({...object, [key]: value}),
    {}
);

const object = pairs.reduce(
    (object, [key, value]) => ({...object, [key]: value}),
    Object.create(null)
);

const object = pairs.reduce(
    (object, [key, value]) => Object.assign(object, {[key]: value}),
    {}
);

const object = _.fromPairs(pairs);

Prefer Array From Map


Prefer using the mapFn callback of Array.from over an immediate .map() call on the Array.from result.

https://github.com/freaktechnik/eslint-plugin-array-func#from-map

👍 Examples of correct code

Array.from(iterable).map((t) => t.id);

Array.from(iterable, (t) => t.id).map((id) => id[0]);

👎 Examples of incorrect code

Array.from(iterable, (t) => t.id);

Array.from(iterable, function(t) { this.format(t); }, this);

const arr = Array.from(iterable);
const mappedArray = arr.map((t) => t.id);

Prefer Array Flat


Use .flat() to flatten an array of arrays. This rule currently recognizes two patterns and can replace them with a .flat() call:

https://github.com/freaktechnik/eslint-plugin-array-func#prefer-flat https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-array-flat.md

👍 Examples of correct code

const concatFlat = array.flat();

const reverseFlat = array.reduce((p, n) => n.concat(p), []);

const otherReduce = array.reduce((p, n) => n + p, 0);

👎 Examples of incorrect code

const concatFlat = [].concat(...array);

const reduceFlat = array.reduce((p, n) => p.concat(n), []);

This Pattern


  • Enforces consistent naming when capturing the current execution context.
  • Disallows this keywords outside of classes or class-like objects.

https://eslint.org/docs/rules/consistent-this#consistent-this

👍 Examples of correct code

var bar = function() {};

const cat = {
  meow: function() {}
}

class C {
    #bar = function() {};
    baz = function() {};
}

quux ??= function() {};

(function bar() {
    // ...
}())

export default function foo() {}

👎 Examples of incorrect code

var that = 42;

var self = this;

that = 42;

self = this;

this.a = 0;
baz(() => this);

(function() {
    this.a = 0;
    baz(() => this);
})();

function foo() {
    this.a = 0;
    baz(() => this);
}

var foo = function() {
    this.a = 0;
    baz(() => this);
};

Use Dot


Enforces use dot notation

https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/dot-notation.md https://eslint.org/docs/rules/dot-notation

👍 Examples of correct code

var x = foo.bar;

var x = foo[bar];

👎 Examples of incorrect code

var x = foo["bar"];

Use This


Enforces that this is used when only this type is returned.

https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/prefer-return-this-type.md

👍 Examples of correct code

class Foo {
  f1(): this {
    return this;
  }
  f2() {
    return this;
  }
  f3 = (): this => {
    return this;
  };
  f4 = () => {
    return this;
  };
}

class Base {}
class Derived extends Base {
  f(): Base {
    return this;
  }
}

👎 Examples of incorrect code

class Foo {
  f1(): Foo {
    return this;
  }
  f2 = (): Foo => {
    return this;
  };
  f3(): Foo | undefined {
    return Math.random() > 0.5 ? this : undefined;
  }
}

Use Is-Nan


Require calls to isNaN() when checking for NaN

https://eslint.org/docs/latest/rules/use-isnan

👍 Examples of correct code

if (isNaN(foo)) {
    // ...
}

if (!isNaN(foo)) {
    // ...
}

👎 Examples of incorrect code

if (foo == NaN) {
    // ...
}

if (foo != NaN) {
    // ...
}

if (foo == Number.NaN) {
    // ...
}

if (foo != Number.NaN) {
    // ...
}

Dot Object Format


  • The dot in a member expression should be on the same line as the property portion.
  • Disallows whitespace before properties.

https://eslint.org/docs/rules/dot-location#dot-location https://eslint.org/docs/rules/no-whitespace-before-property

👍 Examples of correct code

foo.bar

foo[bar]

foo[ bar ]

foo.bar.baz

foo
  .bar().baz()

foo
  .bar()
  .baz()

👎 Examples of incorrect code

foo [bar]

foo. bar

foo .bar

foo. bar. baz

foo. bar()
  .baz()

foo
  .bar(). baz()

No Trailing Space


Not allow trailing whitespace

https://eslint.org/docs/rules/dot-location#dot-location https://eslint.org/docs/rules/no-whitespace-before-property

👍 Examples of correct code

var foo = 0;
var baz = 5;

class A {

  b = 1;

}

👎 Examples of incorrect code

var foo = 0;//•••••
var baz = 5;//••

class A {
//••
  b = 1;
//••
}
//••

Type Format


Require consistent spacing around type annotations.

https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/type-annotation-spacing.md

👍 Examples of correct code

let foo: string = "bar";

function foo(): string {}

class Foo {
    name: string;
}

type Foo = () => {};

👎 Examples of incorrect code

let foo:string = "bar";
let foo :string = "bar";
let foo : string = "bar";

function foo():string {}
function foo() :string {}
function foo() : string {}

class Foo {
    name:string;
}

class Foo {
    name :string;
}

class Foo {
    name : string;
}

type Foo = ()=>{};
type Foo = () =>{};
type Foo = ()=> {};

Max Statements Per Line


This rule enforces a maximum number of statements allowed per line.

https://eslint.org/docs/rules/max-statements-per-line

👍 Examples of correct code

var bar, baz;
if (condition) bar = 1;
for (var i = 0; i < length; ++i);
switch (discriminant) { default: }
function foo() { }
var foo = function foo() { };
(function foo() { })();

👎 Examples of incorrect code

var bar; var baz;
if (condition) { bar = 1; }
for (var i = 0; i < length; ++i) { bar = 1; }
switch (discriminant) { default: break; }
function foo() { bar = 1; }
var foo = function foo() { bar = 1; };
(function foo() { bar = 1; })();

No Constant Condition


Disallows constant expressions in conditions. always use variables instead.

https://eslint.org/docs/rules/no-constant-condition#no-constant-condition

👍 Examples of correct code

if (x === 0) {
    doSomething();
}

for (let i = 0; i < 2; i++) {

}

while (typeof x === "undefined") {
    doSomething();
}

do {
    doSomething();
} while (x);

var result = x !== 0 ? a : b;

👎 Examples of incorrect code

if (false) {
    doSomethingUnfinished();
}

if (void x) {
    doSomethingUnfinished();
}

if (x &&= false) {
    doSomethingNever();
}

if (class {}) {
    doSomethingAlways();
}

if (new Boolean(x)) {
    doSomethingAlways();
}

if (Boolean(1)) {
    doSomethingAlways();
}

if (undefined) {
    doSomethingUnfinished();
}

if (x ||= true) {
    doSomethingAlways();
}

for (;-2;) {
    doSomethingForever();
}

while (typeof x) {
    doSomethingForever();
}

do {
    doSomethingForever();
} while (x = -1);

var result = 0 ? a : b;

No Debugger


Debugger not recommended use break point.

https://eslint.org/docs/rules/no-debugger#no-debugger

👍 Examples of correct code

function isTruthy(x) {
    return Boolean(x); // set a breakpoint at this line
}

👎 Examples of incorrect code

function isTruthy(x) {
    debugger;
    return Boolean(x);
}

Not Duplicate Case


No Duplicate case in switch

https://eslint.org/docs/rules/no-duplicate-case#no-duplicate-case

👍 Examples of correct code

switch (a) {
    case 1:
        break;
    case 2:
        break;
    case 3:
        break;
    default:
        break;
}

switch (a) {
    case one:
        break;
    case two:
        break;
    case three:
        break;
    default:
        break;
}

switch (a) {
    case "1":
        break;
    case "2":
        break;
    case "3":
        break;
    default:
        break;

👎 Examples of incorrect code

switch (a) {
    case 1:
        break;
    case 2:
        break;
    case 1:         // duplicate test expression
        break;
    default:
        break;
}

switch (a) {
    case one:
        break;
    case 2:
        break;
    case one:         // duplicate test expression
        break;
    default:
        break;
}

switch (a) {
    case "1":
        break;
    case "2":
        break;
    case "1":         // duplicate test expression
        break;
    default:
        break;
}

Regex Block


  • Disallows empty character classes in regular expressions.
  • No Invalid Regex

https://eslint.org/docs/rules/no-empty-character-class#no-empty-character-class

👍 Examples of correct code

/^abc/.test("abcdefg"); // true
"abcdefg".match(/^abc/); // ["abc"]

/^abc[a-z]/.test("abcdefg"); // true
"abcdefg".match(/^abc[a-z]/); // ["abcd"]

// valid regex
RegExp('.')
new RegExp
this.RegExp('[')

👎 Examples of incorrect code

/^abc[]/.test("abcdefg"); // false
"abcdefg".match(/^abc[]/); // null

// invalid regex
RegExp('[')
RegExp('.', 'z')
new RegExp('\\')

No Overwrite Exception


Disallows empty character classes in regular expressions.

https://eslint.org/docs/rules/no-ex-assign#no-ex-assign

👍 Examples of correct code

try {
    // code
} catch (e) {
    var foo = 10;
}

👎 Examples of incorrect code

try {
    // code
} catch (e) {
    e = 10;
}

No Extra Semi


Disallows unnecessary semicolons.

https://eslint.org/docs/rules/no-extra-semi#no-extra-semi

👍 Examples of correct code

var x = 5;

function foo() {
    // code
}

var bar = function() {
    // code
};

class C {
    field;

    method() {
        // code
    }

    static {
        // code
    }
}

👎 Examples of incorrect code

var x = 5;;

function foo() {
    // code
};

class C {
    field;;

    method() {
        // code
    };

    static {
        // code
    };
};

No Function Overwrite


Disallows reassigning function declarations.

https://eslint.org/docs/rules/no-func-assign#no-func-assign

👍 Examples of correct code

var foo = function () {}
foo = bar;

function foo(foo) { // `foo` is shadowed.
}

👎 Examples of incorrect code

function foo() {}
foo = bar;

function foo() {
    foo = bar;
}

var a = function hello() {
  hello = 123;
};

No Delete Var


Disallow deleting variables.

https://eslint.org/docs/latest/rules/no-delete-var

👍 Examples of correct code

// don't remove

👎 Examples of incorrect code

var x;
delete x;

No Lone Blocks


Disallow unnecessary nested blocks

https://eslint.org/docs/latest/rules/no-lone-blocks

👍 Examples of correct code

while (foo) {
    bar();
}

if (foo) {
    if (bar) {
        baz();
    }
}

function bar() {
    baz();
}

{
    let x = 1;
}

{
    const y = 1;
}

{
    class Foo {}
}

aLabel: {
}

class C {
    static {
        lbl: {
            if (something) {
                break lbl;
            }

            foo();
        }
    }
}

👎 Examples of incorrect code

if (foo) {
    bar();
    {
        baz();
    }
}

function bar() {
    {
        baz();
    }
}

{
    function foo() {}
}

{
    aLabel: {
    }
}

class C {
    static {
        {
            foo();
        }
    }
}

No Proto


Disallow the use of the proto property

https://eslint.org/docs/latest/rules/no-proto

👍 Examples of correct code

var a = Object.getPrototypeOf(obj);

Object.setPrototypeOf(obj, b);

var c = { __proto__: a };

👎 Examples of incorrect code

var a = obj.__proto__;

var a = obj["__proto__"];

obj.__proto__ = b;

obj["__proto__"] = b;

No Declare in Block


Disallows variable or function declarations in nested blocks.

https://eslint.org/docs/rules/no-func-assign#no-func-assign

👍 Examples of correct code

function doSomething() { }

function doSomethingElse() {
    function doAnotherThing() { }
}

class C {
    static {
        function doSomething() { }
    }
}

if (test) {
    asyncCall(id, function (err, data) { });
}

var fn;
if (test) {
    fn = function fnExpression() { };
}

if (foo) var a;

👎 Examples of incorrect code

if (test) {
    function doSomething() { }
}

function doSomethingElse() {
    if (test) {
        function doAnotherThing() { }
    }
}

if (foo) function f(){}

class C {
    static {
        if (test) {
            function doSomething() { }
        }
    }
}

No Nonoctal Decimal Escape


Disallow \8 and \9 escape sequences in string literals

https://eslint.org/docs/latest/rules/no-nonoctal-decimal-escape

👍 Examples of correct code

"8";

"9";

var foo = "w8less";

var bar = "December 19";

var baz = "Don't use \\8 and \\9 escapes.";

var quux = "\0\u0038";

👎 Examples of incorrect code

"\8";

"\9";

var foo = "w\8less";

var bar = "December 1\9";

var baz = "Don't use \8 and \9 escapes.";

var quux = "\0\8";

No Import Absolute Path


Node.js allows the import of modules using an absolute path such as /home/xyz/file.js. That is a bad practice as it ties the code using it to your computer, and therefore makes it unusable in packages distributed on npm for instance.

https://github.com/import-js/eslint-plugin-import/blob/HEAD/docs/rules/no-absolute-path.md

👍 Examples of correct code

import _ from 'lodash';
import foo from 'foo';
import foo from './foo';

var _ = require('lodash');
var foo = require('foo');
var foo = require('./foo');

👎 Examples of incorrect code

import f from '/foo';
import f from '/some/path';

var f = require('/foo');
var f = require('/some/path');

No Webpack Loader Syntax


Forbid Webpack loader syntax in imports.

https://github.com/import-js/eslint-plugin-import/blob/HEAD/docs/rules/no-webpack-loader-syntax.md

👍 Examples of correct code

import myModule from 'my-module';
import theme from './theme.css';

var myModule = require('my-module');
var theme = require('./theme.css');

👎 Examples of incorrect code

import myModule from 'my-loader!my-module';
import theme from 'style!css!./theme.css';

var myModule = require('my-loader!./my-module');
var theme = require('style!css!./theme.css');

No Magic Number


Disallow magic numbers

https://eslint.org/docs/latest/rules/no-magic-numbers

👍 Examples of correct code

var TAX = 0.25;

var dutyFreePrice = 100,
    finalPrice = dutyFreePrice + (dutyFreePrice * TAX);

👎 Examples of incorrect code

var dutyFreePrice = 100,
    finalPrice = dutyFreePrice + (dutyFreePrice * 0.25);

// or

var data = ['foo', 'bar', 'baz'];

var dataLast = data[2];

Security Negation


Disallows variable or function declarations in nested blocks.

https://eslint.org/docs/rules/no-negated-in-lhs#no-negated-in-lhs

👍 Examples of correct code

if(!(key in object)) {
    // key is not in object
}

👎 Examples of incorrect code

if(!key in object) {
    // operator precedence makes it equivalent to (!key) in object
    // and type conversion makes it equivalent to (key ? "false" : "true") in object
}

Regex Space


Disallows multiple spaces in regular expression literals.

https://eslint.org/docs/rules/no-regex-spaces#no-regex-spaces

👍 Examples of correct code

var re = /foo {3}bar/;
var re = new RegExp("foo {3}bar");

// better
var re = /foo {3}bar/;
var re = new RegExp("foo\s{3}bar");

👎 Examples of incorrect code

var re = /foo   bar/;
var re = new RegExp("foo   bar");

Array No Space


Disallows sparse arrays.

https://eslint.org/docs/rules/no-sparse-arrays#no-sparse-arrays

👍 Examples of correct code

var items = [];
var items = new Array(23);

// trailing comma (after the last element) is not a problem
var colors = [ "red", "blue", ];

👎 Examples of incorrect code

var items = [,];
var colors = [ "red",, "blue" ];

Valid Type-Of


Enforces comparing typeof expressions against valid strings.

https://eslint.org/docs/rules/valid-typeof#valid-typeof

👍 Examples of correct code

typeof foo === "string"
typeof bar == "undefined"
typeof foo === baz
typeof bar === typeof qux

👎 Examples of incorrect code

typeof foo === "strnig"
typeof foo == "undefimed"
typeof bar != "nunber"
typeof bar !== "fucntion"

Strict equality


Requires the use of === and !== instead of == and !=. It is considered good practice to use the type-safe equality operators === and !== instead of their regular counterparts == and !=.

https://eslint.org/docs/rules/eqeqeq#eqeqeq

👍 Examples of correct code

a === b
foo === true
bananas !== 1
value === undefined
typeof foo === 'undefined'
'hello' !== 'world'
0 === 0
true === true
foo === null

👎 Examples of incorrect code

a == b
foo == true
bananas != 1
value == undefined
typeof foo == 'undefined'
'hello' != 'world'
0 == 0
true == true
foo == null

No Label


  • Disallows unnecessary labels.
  • Labeled statements in JavaScript are used in conjunction with break and continue to control flow around multiple loops. For example:

https://eslint.org/docs/rules/no-extra-label#no-extra-label https://eslint.org/docs/rules/no-labels#no-labels

👍 Examples of correct code

while (a) {
    break;
}

for (let i = 0; i < 10; ++i) {
    break;
}

switch (a) {
    case 0:
        break;
}

👎 Examples of incorrect code

A: while (a) {
    break A;
}

B: for (let i = 0; i < 10; ++i) {
    break B;
}

C: switch (a) {
    case 0:
        break C;
}

Full Decimal Number


Disallows leading or trailing decimal points in numeric literals.

https://eslint.org/docs/rules/no-floating-decimal#no-floating-decimal

👍 Examples of correct code

var num = 0.5;
var num = 2.0;
var num = -0.7;

👎 Examples of incorrect code

var num = .5;
var num = 2.;
var num = -.7;

No Global Overwrite


Disallows reassignment of native objects.

https://eslint.org/docs/rules/no-floating-decimal#no-floating-decimal

👍 Examples of correct code

a = 1
var b = 1
b = 2

onload = function() {}

/*global a:writable*/
a = 1

👎 Examples of incorrect code

Object = null;
undefined = 1;
window = {};
length = 1;
top = 1;

/*global a:readonly*/
a = 1

Not Used New


Disallows new operators outside of assignments or comparisons.

https://eslint.org/docs/rules/no-new#no-new

👍 Examples of correct code

var thing = new Thing();

Thing();

👎 Examples of incorrect code

new Thing();

No New Function


Disallows new operators with the Function object. It's possible to create functions in JavaScript from strings at runtime using the Function constructor, such as:

https://eslint.org/docs/rules/no-new-func#no-new-func

👍 Examples of correct code

var x = function (a, b) {
    return a + b;
};

👎 Examples of incorrect code

var x = new Function("a", "b", "return a + b");
var x = Function("a", "b", "return a + b");
var x = Function.call(null, "a", "b", "return a + b");
var x = Function.apply(null, ["a", "b", "return a + b"]);
var x = Function.bind(null, "a", "b", "return a + b")();

// assuming that the result of Function.bind(...) will be eventually called.
var f = Function.bind(null, "a", "b", "return a + b");

No Redeclare


Disallows variable redeclarations.

https://eslint.org/docs/rules/no-redeclare#no-redeclare https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-redeclare.md

👍 Examples of correct code

var a = 3;
a = 10;

class C {
    foo() {
        var b = 3;
        b = 10;
    }

    static {
        var c = 3;
        c = 10;
    }
}

👎 Examples of incorrect code

var a = 3;
var a = 10;

class C {
    foo() {
        var b = 3;
        var b = 10;
    }

    static {
        var c = 3;
        var c = 10;
    }
}

No Self Compare


Disallows comparisons where both sides are exactly the same.

https://eslint.org/docs/rules/no-self-compare#no-self-compare

👍 Examples of correct code

var x = 10;
var y = 10;
if (x === y) {
    x = 20;
}

👎 Examples of incorrect code

var x = 10;
if (x === x) {
    x = 20;
}

Loop Valid


Disallows unmodified conditions of loops.

https://eslint.org/docs/rules/no-unmodified-loop-condition#no-unmodified-loop-condition

👍 Examples of correct code

while (node) {
    doSomething(node);
    node = node.parent;
}

for (var j = 0; j < items.length; ++j) {
    doSomething(items[j]);
}

// OK, the result of this binary expression is changed in this loop.
while (node !== root) {
    doSomething(node);
    node = node.parent;
}

// OK, the result of this ternary expression is changed in this loop.
while (node ? A : B) {
    doSomething(node);
    node = node.parent;
}

// A property might be a getter which has side effect...
// Or "doSomething" can modify "obj.foo".
while (obj.foo) {
    doSomething(obj);
}

// A function call can return various values.
while (check(obj)) {
    doSomething(obj);
}

👎 Examples of incorrect code

var node = something;

while (node) {
    doSomething(node);
}
node = other;

for (var j = 0; j < items.length; ++i) {
    doSomething(items[j]);
}

while (node !== root) {
    doSomething(node);
}

Useless Scape


Disallows unnecessary escape characters.

https://eslint.org/docs/rules/no-useless-escape#no-useless-escape

👍 Examples of correct code

"\"";
'\'';
"\x12";
"\u00a9";
"\371";
"xs\u2111";
`\``;
`\${${foo}}`;
`$\{${foo}}`;
/\\/g;
/\t/g;
/\w\$\*\^\./;
/[[]/;
/[\]]/;
/[a-z-]/;

👎 Examples of incorrect code

"\'";
'\"';
"\#";
"\e";
`\"`;
`\"${foo}\"`;
`\#{foo}`;
/\!/;
/\@/;
/[\[]/;
/[a-z\-]/;

No Yoda


Disallows "Yoda" conditions.

https://eslint.org/docs/rules/yoda#yoda

Yoda conditions are so named because the literal value of the condition comes first while the variable comes second. For example, the following is a Yoda condition:

👍 Examples of correct code

if (5 & value) {
    // ...
}

if (value === "red") {
    // ...
}

if (value === `red`) {
    // ...
}

if (`${value}` === `red`) {

}

👎 Examples of incorrect code

if ("red" === color) {
    // ...
}

if (`red` === color) {
    // ...
}

if (`red` === `${color}`) {
    // ...
}

if (true == flag) {
    // ...
}

if (5 > count) {
    // ...
}

if (-1 < str.indexOf(substr)) {
    // ...
}

if (0 <= x && x < 1) {
    // ...
}

No Undefined declare


Disallows initializing variables to undefined.

https://eslint.org/docs/rules/no-undef-init#no-undef-init

👍 Examples of correct code

var foo;
let bar;

const foo = undefined;

let { bar = undefined } = baz;

[quux = undefined] = quuux;

(foo = undefined) => {};

class Foo {
    bar = undefined;
}

👎 Examples of incorrect code

var foo = undefined;
let bar = undefined;

No New require


Disallows new operators with calls to require.

https://eslint.org/docs/rules/no-new-require#no-new-require

👍 Examples of correct code

var AppHeader = require('app-header');
var appHeader = new AppHeader();

👎 Examples of incorrect code

var appHeader = new require('app-header');

No New Object


Disallow Object constructors

https://eslint.org/docs/rules/no-new-object

👍 Examples of correct code

var myObject = new CustomObject();

var myObject = {};

var Object = function Object() {};
new Object();

👎 Examples of incorrect code

var myObject = new Object();

new Object();

No New Symbol


Disallow new operators with the Symbol object

https://eslint.org/docs/latest/rules/no-new-symbol

👍 Examples of correct code

var foo = Symbol('foo');

// Ignores shadowed Symbol.
function bar(Symbol) {
    const baz = new Symbol("baz");
}

👎 Examples of incorrect code

var foo = new Symbol('foo');

Var Size


Enforce minimum identifier lengths

https://eslint.org/docs/latest/rules/id-length

👍 Examples of correct code

var num = 5;
function _f() { return 42; }
function _func() { return 42; }
obj.el = document.body;
var foo = function (evt) { /* do stuff */ };
try {
    dangerousStuff();
} catch (error) {
    // ignore as many do
}
var myObj = { apple: 1 };
(num) => { num * num };
function foo(num = 0) { }
class MyClass { }
class Foo { method() {} }
class Foo { #method() {} }
class Foo { field = 1 }
class Foo { #field = 1 }
function foo(...args) { }
function foo([longName]) { }
var { prop } = {};
var { prop: [longName] } = {};
var [longName] = arr;
function foo({ prop }) { }
function foo({ a: prop }) { }
var { prop } = {};
var { a: prop } = {};
({ prop: obj.longName } = {});
var data = { "x": 1 };  // excused because of quotes
data["y"] = 3;  // excused because of calculated property access

👎 Examples of incorrect code

var x = 5;
obj.e = document.body;
var foo = function (e) { };
try {
    dangerousStuff();
} catch (e) {
    // ignore as many do
}
var myObj = { a: 1 };
(a) => { a * a };
class x { }
class Foo { x() {} }
class Foo { #x() {} }
class Foo { x = 1 }
class Foo { #x = 1 }
function foo(...x) { }
function foo([x]) { }
var [x] = arr;
var { prop: [x]} = {};
function foo({x}) { }
var { x } = {};
var { prop: a} = {};
({ prop: obj.x } = {});

Max Depth


Enforce a maximum depth that blocks can be nested

https://eslint.org/docs/latest/rules/max-depth

👍 Examples of correct code

function foo() {
    for (;;) { // Nested 1 deep
        while (true) { // Nested 2 deep
            if (true) { // Nested 3 deep
            }
        }
    }
}

👎 Examples of incorrect code

function foo() {
    for (;;) { // Nested 1 deep
        while (true) { // Nested 2 deep
            if (true) { // Nested 3 deep
                if (true) { // Nested 4 deep
                    if (true) { // Nested 5 deep
                    }
                }
            }
        }
    }
}

Max Params


Enforce a maximum number of parameters in function definitions

https://eslint.org/docs/latest/rules/max-params https://www.npmjs.com/package/eslint-plugin-better-max-params

👍 Examples of correct code

function foo (bar, baz, qux) {
    doSomething();
}

let foo = (bar, baz, qux) => {
    doSomething();
};

👎 Examples of incorrect code

function foo (bar, baz, qux, qxx) {
    doSomething();
}

let foo = (bar, baz, qux, qxx) => {
    doSomething();
};

Max Statements


Enforce a maximum number of parameters in function definitions

https://eslint.org/docs/latest/rules/max-statements

👍 Examples of correct code

function foo() {
  var foo1 = 1;
  var foo2 = 2;
  var foo3 = 3;
  var foo4 = 4;
  var foo5 = 5;
  var foo6 = 6;
  var foo7 = 7;
  var foo8 = 8;
  var foo9 = 9;
  var foo10 = 10;
  return function () {

    // The number of statements in the inner function does not count toward the
    // statement maximum.

    return 42;
  };
}

let foo = () => {
  var foo1 = 1;
  var foo2 = 2;
  var foo3 = 3;
  var foo4 = 4;
  var foo5 = 5;
  var foo6 = 6;
  var foo7 = 7;
  var foo8 = 8;
  var foo9 = 9;
  var foo10 = 10;
  return function () {

    // The number of statements in the inner function does not count toward the
    // statement maximum.

    return 42;
  };
}

👎 Examples of incorrect code

function foo() {
  var foo1 = 1;
  var foo2 = 2;
  var foo3 = 3;
  var foo4 = 4;
  var foo5 = 5;
  var foo6 = 6;
  var foo7 = 7;
  var foo8 = 8;
  var foo9 = 9;
  var foo10 = 10;

  var foo11 = 11; // Too many.
}

let foo = () => {
  var foo1 = 1;
  var foo2 = 2;
  var foo3 = 3;
  var foo4 = 4;
  var foo5 = 5;
  var foo6 = 6;
  var foo7 = 7;
  var foo8 = 8;
  var foo9 = 9;
  var foo10 = 10;

  var foo11 = 11; // Too many.
};

Operator Assignment


Require or disallow assignment operator shorthand where possible

https://eslint.org/docs/latest/rules/operator-assignment

👍 Examples of correct code

x = y;
x += y;
x = y * z;
x = (x * y) * z;
x[0] /= y;
x[foo()] = x[foo()] % 2;
x = y + x; // `+` is not always commutative (e.g. x = "abc")

👎 Examples of incorrect code

x = x + y;
x = y * x;
x[0] = x[0] / y;
x.y = x.y << z;

Require Yield


Require generator functions to contain yield

https://eslint.org/docs/latest/rules/require-yield

👍 Examples of correct code

function* foo() {
  yield 5;
  return 10;
}

function foo() {
  return 10;
}

// This rule does not warn on empty generator functions.
function* foo() { }

👎 Examples of incorrect code

function* foo() {
  return 10;
}

Prefer Rest Params


Require rest parameters instead of arguments

https://eslint.org/docs/latest/rules/prefer-rest-params

👍 Examples of correct code

function foo(...args) {
    console.log(args);
}

function foo(action, ...args) {
    action.apply(null, args); // or `action(...args)`, related to the `prefer-spread` rule.
}

// Note: the implicit arguments can be overwritten.
function foo(arguments) {
    console.log(arguments); // This is the first argument.
}
function foo() {
    var arguments = 0;
    console.log(arguments); // This is a local variable.
}

👎 Examples of incorrect code

function foo() {
    console.log(arguments);
}

function foo(action) {
    var args = Array.prototype.slice.call(arguments, 1);
    action.apply(null, args);
}

function foo(action) {
    var args = [].slice.call(arguments, 1);
    action.apply(null, args);
}

Symbol Description


Require symbol descriptions

https://eslint.org/docs/latest/rules/symbol-description

👍 Examples of correct code

var foo = Symbol("some description");

// or

var someString = "some description";
var bar = Symbol(someString);

👎 Examples of incorrect code

var foo = Symbol();

No Await Return


Disallow unnecessary return await

https://eslint.org/docs/latest/rules/no-return-await

👍 Examples of correct code

async function foo() {
    return bar();
}

async function foo() {
    await bar();
    return;
}

// This is essentially the same as `return await bar();`, but the rule checks only `await` in `return` statements
async function foo() {
    const x = await bar();
    return x;
}

// In this example the `await` is necessary to be able to catch errors thrown from `bar()`
async function foo() {
    try {
        return await bar();
    } catch (error) {}
}

👎 Examples of incorrect code

async function foo() {
    return await bar();
}

Max Class Per File


Enforce a maximum 1 classes per file

https://eslint.org/docs/latest/rules/max-classes-per-file

👍 Examples of correct code

class Foo {}

👎 Examples of incorrect code

class Foo {}
class Bar {}

No Constructor Return


Disallow returning value from constructor

https://eslint.org/docs/latest/rules/no-constructor-return

👍 Examples of correct code

class C {
    constructor(c) {
        this.c = c;
    }
}

class D {
    constructor(f) {
        if (!f) {
            return;  // Flow control.
        }

        f();
    }
}

👎 Examples of incorrect code

class A {
    constructor(a) {
        this.a = a;
        return a;
    }
}

class B {
    constructor(f) {
        if (!f) {
            return 'falsy';
        }
    }
}

Prefer Exponentiation Operator


Prefira o operador de exponencial

https://eslint.org/docs/latest/rules/prefer-exponentiation-operator

👍 Examples of correct code

const foo = 2 ** 8;

const bar = a ** b;

let baz = (a + b) ** (c + d);

let quux = (-1) ** n;

👎 Examples of incorrect code

const foo = Math.pow(2, 8);

const bar = Math.pow(a, b);

let baz = Math.pow(a + b, c + d);

let quux = Math.pow(-1, n);

Prefer Object Spread


Disallow using Object.assign with an object literal as the first argument and prefer the use of object spread instead.

https://eslint.org/docs/latest/rules/prefer-object-spread

👍 Examples of correct code

({ ...foo });

({ ...baz, foo: 'bar' });

// Any Object.assign call without an object literal as the first argument
Object.assign(foo, { bar: baz });

Object.assign(foo, bar);

Object.assign(foo, { bar, baz });

Object.assign(foo, { ...baz });

👎 Examples of incorrect code

Object.assign({}, foo);

Object.assign({}, {foo: 'bar'});

Object.assign({ foo: 'bar'}, baz);

Object.assign({}, baz, { foo: 'bar' });

Object.assign({}, { ...baz });

// Object.assign with a single argument that is an object literal
Object.assign({});

Object.assign({ foo: bar });

Accessor Pairs


Enforce getter and setter pairs in objects and classes

https://eslint.org/docs/latest/rules/accessor-pairs

👍 Examples of correct code

var o = {
    set a(value) {
        this.val = value;
    },
    get a() {
        return this.val;
    }
};

var myObject = { d: 1 };
Object.defineProperty(myObject, 'c', {
    set: function(value) {
        this.val = value;
    },
    get: function() {
        return this.val;
    }
});

👎 Examples of incorrect code

var o = {
    set a(value) {
        this.val = value;
    }
};

var myObject = { d: 1 };
Object.defineProperty(myObject, 'c', {
    set: function(value) {
        this.val = value;
    }
});

Default Case Last


Enforce default clauses in switch statements to be last

https://eslint.org/docs/latest/rules/default-case-last

👍 Examples of correct code

👎 Examples of incorrect code

switch (foo) {
    default:
        bar();
        break;
    case "a":
        baz();
        break;
}

switch (foo) {
    case 1:
        bar();
        break;
    default:
        baz();
        break;
    case 2:
        quux();
        break;
}

switch (foo) {
    case "x":
        bar();
        break;
    default:
    case "y":
        baz();
        break;
}

switch (foo) {
    default:
        break;
    case -1:
        bar();
        break;
}

switch (foo) {
  default:
    doSomethingIfNotZero();
  case 0:
    doSomethingAnyway();
}

Prefer Literals


Suggests using template literals instead of string concatenation.

https://eslint.org/docs/rules/prefer-template#prefer-template

👍 Examples of correct code

var str = "Hello World!";
var str = `Hello, ${name}!`;
var str = `Time: ${12 * 60 * 60 * 1000}`;

// This is reported by `no-useless-concat`.
var str = "Hello, " +
  "World!";

👎 Examples of incorrect code

var str = "Hello, " + name + "!";
var str = "Time: " + (12 * 60 * 60 * 1000);

Useless Condition


Prevents conditionals where the type is always truthy or always falsy.

https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-unnecessary-condition.md

👍 Examples of correct code

function head<T>(items: T[]) {
  // Necessary, since items.length might be 0
  if (items.length) {
    return items[0].toUpperCase();
  }
}

function foo(arg: string) {
  // Necessary, since foo might be ''.
  if (arg) {
  }
}

function bar(arg?: string | null) {
  // Necessary, since arg might be nullish
  return arg?.length;
}

[0, 1, 2, 3].filter(t => t); // number can be truthy or falsy

👎 Examples of incorrect code

function head<T>(items: T[]) {
  // items can never be nullable, so this is unnecessary
  if (items) {
    return items[0].toUpperCase();
  }
}

function foo(arg: 'bar' | 'baz') {
  // arg is never nullable or empty string, so this is unnecessary
  if (arg) {
  }
}

function bar<T>(arg: string) {
  // arg can never be nullish, so ?. is unnecessary
  return arg?.length;
}

// Checks array predicate return types, where possible
[
  [1, 2],
  [3, 4],
].filter(t => t); // number[] is always truthy

No multiple empty line


we should avoid using lots of white spaces, this takes up the screen and tries to supply a bad organization with spaces

https://eslint.org/docs/rules/no-multiple-empty-lines

👍 Examples of correct code

function foo<T>(items: T[]) {

}

function bar(arg: string) {

}

👎 Examples of incorrect code

function foo<T>(items: T[]) {
// \r\n
// \r\n
}
// \n
// \n
function bar(arg: string) {
// \n
// \n
}

No Misused New


Block misused new instance

https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-misused-new.md

👍 Examples of correct code

class C {
  constructor() {}
}
interface I {
  new (): C;
}

👎 Examples of incorrect code

class C {
  new(): C;
}

interface I {
  new (): I;
  constructor(): void;
}

No Semicolon Before spacing


Disallows space before semicolon.

https://eslint.org/docs/rules/semi-spacing

👍 Examples of correct code

var foo;
var foo; var bar;
throw new Error("error");
while (a) { break; }
for (i = 0; i < 10; i++) {}

👎 Examples of incorrect code

var foo ;
var foo;var bar;
throw new Error("error") ;
while (a) { break ; }
for (i = 0 ; i < 10 ; i++) {}
for (i = 0;i < 10;i++) {}

Disallow Type


Disallow specific types from being used. Disallow any use.

https://typescript-eslint.io/rules/ban-types https://typescript-eslint.io/rules/no-explicit-any

👍 Examples of correct code

// use lower-case primitives for consistency
const str: string = 'foo';
const bool: boolean = true;
const num: number = 1;
const symb: symbol = Symbol('foo');

// use a proper function type
const func: () => number = () => 1;

// use safer object types
const lowerObj: object = {};

const capitalObj1: number = 1;
const capitalObj2: { a: string } = { a: 'string' };

const curly1: number = 1;
const curly2: Record<'a', string> = { a: 'string' };

interface ObjInterface {
    a: number
}
const obj: ObjInterface = { a: 1 };

👎 Examples of incorrect code

// use lower-case primitives for consistency
const str: String = 'foo';
const bool: Boolean = true;
const num: Number = 1;
const symb: Symbol = Symbol('foo');

// use a proper function type
const func: Function = () => 1;

// use safer object types
const capitalObj1: Object = 1;
const capitalObj2: Object = { a: 'string' };

const curly1: {} = 1;
const curly2: {} = { a: 'string' };

const obj: any = { a: 1 };

Disallow Empty Function


Disallow empty functions

https://typescript-eslint.io/rules/no-empty-function

👍 Examples of correct code

function foo() {
    // do nothing.
}

var foo = function() {
    // any clear comments.
};

var foo = () => {
    bar();
};

function* foo() {
    // do nothing.
}

var foo = function*() {
    // do nothing.
};

var obj = {
    foo: function() {
        // do nothing.
    },

    foo: function*() {
        // do nothing.
    },

    foo() {
        // do nothing.
    },

    *foo() {
        // do nothing.
    },

    get foo() {
        // do nothing.
    },

    set foo(value) {
        // do nothing.
    }
};

class A {
    constructor() {
        // do nothing.
    }

    foo() {
        // do nothing.
    }

    *foo() {
        // do nothing.
    }

    get foo() {
        // do nothing.
    }

    set foo(value) {
        // do nothing.
    }

    static foo() {
        // do nothing.
    }

    static *foo() {
        // do nothing.
    }

    static get foo() {
        // do nothing.
    }

    static set foo(value) {
        // do nothing.
    }
}

👎 Examples of incorrect code

function foo() {}

var foo = function() {};

var foo = () => {};

function* foo() {}

var foo = function*() {};

var obj = {
    foo: function() {},

    foo: function*() {},

    foo() {},

    *foo() {},

    get foo() {},

    set foo(value) {}
};

class A {
    constructor() {}

    foo() {}

    *foo() {}

    get foo() {}

    set foo(value) {}

    static foo() {}

    static *foo() {}

    static get foo() {}

    static set foo(value) {}
}

Disallow Duplicate Imports


Disallow duplicate imports.

https://typescript-eslint.io/rules/no-duplicate-imports https://github.com/import-js/eslint-plugin-import/blob/HEAD/docs/rules/no-duplicates.md

👍 Examples of correct code

import { merge, find } from "module";

import something from "another-module";
// or
import * as something from "another-module";

👎 Examples of incorrect code

import { merge } from "module";
import something from "another-module";
import { find } from "module";

Disallow Unnecessary Type


Disallows unnecessary constraints on generic types.

https://typescript-eslint.io/rules/no-unnecessary-type-constraint

👍 Examples of correct code

interface Foo<T> {}

type Bar<T> = {};

class Baz<T> {
    qux<U> { }
}

const Quux = <T>() => {};

function Quuz<T>() {}

👎 Examples of incorrect code

interface FooAny<T extends any> {}
interface FooUnknown<T extends unknown> {}

type BarAny<T extends any> = {};
type BarUnknown<T extends unknown> = {};

class BazAny<T extends any> {
  quxUnknown<U extends unknown>() {}
}

class BazUnknown<T extends unknown> {
  quxUnknown<U extends unknown>() {}
}

const QuuxAny = <T extends any>() => {};
const QuuxUnknown = <T extends unknown>() => {};

function QuuzAny<T extends any>() {}
function QuuzUnknown<T extends unknown>() {}

Disallow Caller


The use of arguments.caller and arguments.callee make several code optimizations impossible. They have been deprecated in future versions of JavaScript and their use is forbidden in ECMAScript 5 while in strict mode.

https://eslint.org/docs/rules/no-caller

👍 Examples of correct code

function foo(n) {
    if (n <= 0) {
        return;
    }

    foo(n - 1);
}

[1,2,3,4,5].map(function factorial(n) {
    return !(n > 1) ? 1 : factorial(n - 1) * n;
});

👎 Examples of incorrect code

function foo(n) {
    if (n <= 0) {
        return;
    }

    arguments.callee(n - 1);
}

[1,2,3,4,5].map(function(n) {
    return !(n > 1) ? 1 : arguments.callee(n - 1) * n;
});

Disallow Underscore


This rule disallows dangling underscores in identifiers.

https://eslint.org/docs/rules/no-underscore-dangle

👍 Examples of correct code

var _ = require('underscore');
var obj = _.contains(items, item);
obj.__proto__ = {};
var file = __filename;
function foo(_bar) {};
const foo = { onClick(_bar) {} };
const foo = (_bar) => {};

👎 Examples of incorrect code

var foo_;
var __proto__ = {};
foo._bar();
function _foo(_bar) {};

Disallow Param Reassign


This rule aims to prevent unintended behavior caused by modification or reassignment of function parameters.

https://eslint.org/docs/rules/no-param-reassign

👍 Examples of correct code

function foo(bar) {
    var baz = bar;
}

👎 Examples of incorrect code

function foo(bar) {
    bar = 13;
}

function foo(bar) {
    bar++;
}

function foo(bar) {
    for (bar in baz) {}
}

function foo(bar) {
    for (bar of baz) {}
}

Prefer Const


If a variable is never reassigned, using the const declaration is better.

https://eslint.org/docs/rules/prefer-const https://typescript-eslint.io/rules/prefer-as-const

👍 Examples of correct code

const a = 0;

// it's never initialized.
let a;
console.log(a);

// it's reassigned after initialized.
let a;
a = 0;
a = 1;
console.log(a);

// it's initialized in a different block from the declaration.
let a;
if (true) {
    a = 0;
}
console.log(a);

// it's initialized in a different scope.
let a;
class C {
    #x;
    static {
        a = obj => obj.#x;
    }
}

// it's initialized at a place that we cannot write a variable declaration.
let a;
if (true) a = 0;
console.log(a);

// `i` gets a new binding each iteration
for (const i in [1, 2, 3]) {
  console.log(i);
}

// `a` gets a new binding each iteration
for (const a of [1, 2, 3]) {
  console.log(a);
}

let foo = 'bar';
let foo = 'bar' as const;
let foo: 'bar' = 'bar' as const;
let bar = 'bar' as string;
let foo = <string>'bar';
let foo = { bar: 'baz' };

👎 Examples of incorrect code

let a = 3;
console.log(a);

let a;
a = 0;
console.log(a);

class C {
    static {
        let a;
        a = 0;
        console.log(a);
    }
}

// `i` is redefined (not reassigned) on each loop step.
for (let i in [1, 2, 3]) {
    console.log(i);
}

// `a` is redefined (not reassigned) on each loop step.
for (let a of [1, 2, 3]) {
    console.log(a);
}

let bar: 2 = 2;
let foo = <'bar'>'bar';
let foo = { bar: 'baz' as 'baz' };

Array Type


Requires using either T[] instead of Array<T>.

https://typescript-eslint.io/rules/array-type

👍 Examples of correct code

const x: string[] = ['a', 'b'];
const y: readonly string[] = ['a', 'b'];

const a: Array<string | number> = ['a', 'b'];

👎 Examples of incorrect code

const x: Array<string> = ['a', 'b'];
const y: ReadonlyArray<string> = ['a', 'b'];

Disallow Await sync function


Disallows awaiting a value that is not a Thenable.

https://typescript-eslint.io/rules/await-thenable

👍 Examples of correct code

await Promise.resolve('value');

const createValue = async () => 'value';
await createValue();

👎 Examples of incorrect code

await 'value';

const createValue = () => 'value';
await createValue();

Method Signature Style


Enforces using a particular method signature syntax.

https://typescript-eslint.io/rules/method-signature-style

👍 Examples of correct code

interface T1 {
  func(arg: string): number;
}
type T2 = {
  func(arg: boolean): void;
};
interface T3 {
  func(arg: number): void;
  func(arg: string): void;
  func(arg: boolean): void;
}

👎 Examples of incorrect code

interface T1 {
  func: (arg: string) => number;
}
type T2 = {
  func: (arg: boolean) => void;
};
// this is equivalent to the overload
interface T3 {
  func: ((arg: number) => void) &
    ((arg: string) => void) &
    ((arg: boolean) => void);
}

No Unnecessary Type Assertion


Warns if a type assertion does not change the type of an expression.

https://typescript-eslint.io/rules/no-unnecessary-type-assertion

👍 Examples of correct code

const foo = <number>3;

const foo = 3 as number;
const foo: number = 3;

const foo = 'foo' as const;

👎 Examples of incorrect code

const foo = 3;
const bar = foo!;

const foo = <3>3;

type Foo = 3;
const foo = <Foo>3;

type Foo = 3;
const foo = 3 as Foo;

No Unsafe Call


This rule disallows calling any variable that is typed as any.

https://typescript-eslint.io/rules/no-unsafe-call

👍 Examples of correct code

declare const typedVar: () => void;
declare const typedNested: { prop: { a: () => void } };

typedVar();
typedNested.prop.a();

(() => {})();

new Map();

String.raw`foo`;

👎 Examples of incorrect code

declare const anyVar: any;
declare const nestedAny: { prop: any };

anyVar();
anyVar.a.b();

nestedAny.prop();
nestedAny.prop['a']();

new anyVar();
new nestedAny.prop();

anyVar`foo`;
nestedAny.prop`foo`;

No Var


Requires let or const instead of var.

https://eslint.org/docs/rules/no-var

👍 Examples of correct code

let x = "y";
const CONFIG = {};

// init var is better
let y;
if (CONFIG.y) {
    y = CONFIG.y;
}
console.log(y);

👎 Examples of incorrect code

var x = "y";
var CONFIG = {};

if (CONFIG.y) {
    var y = CONFIG.y;
}
console.log(y);

Operator Break-Line


The operator-linebreak rule is aimed at enforcing a particular operator line break style

https://eslint.org/docs/rules/operator-linebreak

👍 Examples of correct code

foo = 1 + 2;

foo = 1
    + 2
    + 3;

foo = 5;

if (
  someCondition
  || otherCondition
) {
  // code ...
}

answer = everything
  ? 42
  : foo;

class Foo {
    a  = 1;
    [b]  = 2;
    d = 4;
}

👎 Examples of incorrect code

foo = 1 +
      2;

foo =
    5;

foo
    = 5;

if (
    someCondition ||
    otherCondition
) {
}

answer = everything ?
  42 :
  foo;

class Foo {
    a =
        1;
    [b] =
        2;
    [c
    ] =
        3;
}

Generator Function Stars


Enforces spacing before * in generator functions.

https://eslint.org/docs/rules/generator-star-spacing

👍 Examples of correct code

function *generator() {}

var anonymous = function *() {};

var shorthand = { *generator() {} };

👎 Examples of incorrect code

function* generator() {}

var anonymous = function* () {};

var shorthand = { * generator() {} };

No Unsafe Optional Chaining


Enforces spacing before * in generator functions.

https://eslint.org/docs/rules/no-unsafe-optional-chaining

👍 Examples of correct code

(obj?.foo)?.();

obj?.foo();

(obj?.foo ?? bar)();

obj?.foo.bar;

obj.foo?.bar;

foo?.()?.bar;

(obj?.foo ?? bar)`template`;

new (obj?.foo ?? bar)();

var baz = {...obj?.foo};

const { bar } = obj?.foo || baz;

async function foo () {
  const { bar } = await obj?.foo || baz;
   (await obj?.foo)?.();
   (await obj?.foo)?.bar;
}

👎 Examples of incorrect code

(obj?.foo)();

(obj?.foo).bar;

(foo?.()).bar;

(foo?.()).bar();

(obj?.foo ?? obj?.bar)();

(foo || obj?.foo)();

(obj?.foo && foo)();

(foo ? obj?.foo : bar)();

(foo, obj?.bar).baz;

(obj?.foo)`template`;

new (obj?.foo)();

[...obj?.foo];

bar(...obj?.foo);

1 in obj?.foo;

bar instanceof obj?.foo;

for (bar of obj?.foo);

const { bar } = obj?.foo;

[{ bar } = obj?.foo] = [];

with (obj?.foo);

class A extends obj?.foo {}

var a = class A extends obj?.foo {};

async function foo () {
    const { bar } = await obj?.foo;
   (await obj?.foo)();
   (await obj?.foo).bar;
}

Array Callback


Array has several methods for filtering, mapping, and folding. If we forget to write return statement in a callback of those, it's probably a mistake.

https://eslint.org/docs/rules/array-callback-return https://sonarsource.github.io/rspec/#/rspec/S3796/javascript

👍 Examples of correct code

var indexMap = myArray.reduce(function(memo, item, index) {
    memo[item] = index;
    return memo;
}, {});

var foo = Array.from(nodes, function(node) {
    if (node.tagName === "DIV") {
        return true;
    }
    return false;
});

var bar = foo.map(node => node.getAttribute("id"));

👎 Examples of incorrect code

var indexMap = myArray.reduce(function(memo, item, index) {
    memo[item] = index;
}, {});

var foo = Array.from(nodes, function(node) {
    if (node.tagName === "DIV") {
        return true;
    }
});

var bar = foo.filter(function(x) {
    if (x) {
        return true;
    } else {
        return;
    }
});

Space Types


Requires spacing around infix operators.

https://eslint.org/docs/rules/space-infix-ops https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/space-infix-ops.md https://eslint.org/docs/rules/key-spacing

👍 Examples of correct code

a + b

a ? b : c

const a = {b:1};

var {a = 0} = bar;

function foo(a = 0) { }

function foo(a = 0): string | number { }

var obj = { "foo": 42 };

👎 Examples of incorrect code

a+b

a+ b

a +b

a?b:c

const a={b:1};

var {a=0}=bar;

function foo(a=0) { }

function foo(): string|number { }

var obj = { "foo" : 42 };
var obj = { "foo" :42 };

Curly


Requires following curly brace conventions.

https://eslint.org/docs/rules/curly

👍 Examples of correct code

if (foo) {
    bar();
    baz();
} else {
    buz();
}

if (foo) {
    bar();
} else if (faa) {
    bor();
} else {
    other();
    things();
}

if (true)
    foo();
else
    baz();

if (foo)
    foo++;

👎 Examples of incorrect code

if (foo) {
    bar();
    baz();
} else
    buz();

if (foo)
    bar();
else if (faa)
    bor();
else {
    other();
    things();
}

if (true)
    foo();
else {
    baz();
}

if (foo) {
    foo++;
}

Quote Props


Requires quotes around all object literal property names if any name strictly requires quotes, otherwise disallows quotes around object property names.

https://eslint.org/docs/rules/quote-props

👍 Examples of correct code

var object1 = {
    "foo": "bar",
    "baz": 42,
    "qux-lorem": true
};

var object2 = {
    foo: 'bar',
    baz: 42
};

👎 Examples of incorrect code

var object1 = {
    foo: "bar",
    "baz": 42,
    "qux-lorem": true
};

var object2 = {
    'foo': 'bar',
    'baz': 42
};

Brace Style


Enforces consistent brace style for blocks.

https://eslint.org/docs/rules/brace-style

👍 Examples of correct code

function foo() {
  return true;
}

if (foo) {
  bar();
}

if (foo) {
  bar();
} else {
  baz();
}

try {
  somethingRisky();
} catch(e) {
  handleError();
}

class C {
    static {
        foo();
    }
}

// when there are no braces, there are no problems
if (foo) bar();
else if (baz) boom();

👎 Examples of incorrect code

function foo()
{
  return true;
}

if (foo)
{
  bar();
}

try
{
  somethingRisky();
} catch(e)
{
  handleError();
}

if (foo) {
  bar();
}
else {
  baz();
}

class C
{
    static
    {
        foo();
    }
}

Comma Style


This rule enforce consistent comma style in array literals, object literals, and variable declarations.

https://eslint.org/docs/rules/comma-style

👍 Examples of correct code

var foo = 1, bar = 2;

var foo = 1,
    bar = 2;

var foo = ["apples",
           "oranges"];

function bar() {
    return {
        "a": 1,
        "b:": 2
    };
}

👎 Examples of incorrect code

var foo = 1,
    bar = 2;

var foo = ["apples",
           "oranges"];

function bar() {
    return {
        "a": 1,
        "b:": 2
    };
}

Object Break Line


Enforces placing object properties on separate lines.

https://eslint.org/docs/rules/object-property-newline

👍 Examples of correct code

const obj1 = { foo: "foo", bar: "bar", baz: "baz" };

const obj2 = {
    foo: "foo",
    bar: "bar",
    baz: "baz",
};

const user = process.argv[2];
const obj3 = {
    user,
    [ process.argv[3] ? "foo" : "bar" ]: 0,
    baz: [
        1,
        2,
        4,
        8,
    ]
};

👎 Examples of incorrect code

const obj1 = {
    foo: "foo", bar: "bar", baz: "baz"
};

const obj2 = {
    foo: "foo", bar: "bar",
    baz: "baz"
};

const obj3 = {
    [process.argv[3] ? "foo" : "bar"]: 0, baz: [
        1,
        2,
        4,
        8
    ]
};

Object Curly Newline


A number of style guides require or disallow line breaks inside of object braces and other tokens.

https://eslint.org/docs/latest/rules/object-curly-newline

👍 Examples of correct code

let a = {};
let b = { foo: 1 };
let c = { foo: 1, bar: 2 };
let d = {
    foo: 1,
    bar: 2,
};
let e = {
    foo: function() {
        dosomething();
    }
};

let { f } = obj;
let { g, h } = obj;
let {
    i,
    j
} = obj;
let { k = () => dosomething() } = obj;

👎 Examples of incorrect code

let b = {
    foo: 1
};
let c = { foo: 1,
    bar: 2 };
let d = {foo: 1
    , bar: 2};
let e = { foo: function() {
    dosomething();
} };

let {i,
    j} = obj;

No Negative Condition


Negated conditions are more difficult to understand. Code can be made more readable by inverting the condition instead.

https://eslint.org/docs/latest/rules/no-negated-condition

👍 Examples of correct code

if (!a) {
    doSomething();
}

if (!a) {
    doSomething();
} else if (b) {
    doSomething();
}

if (a != b) {
    doSomething();
}

a ? b : c

👎 Examples of incorrect code

if (!a) {
    doSomething();
} else {
    doSomethingElse();
}

if (a != b) {
    doSomething();
} else {
    doSomethingElse();
}

if (a !== b) {
    doSomething();
} else {
    doSomethingElse();
}

!a ? c : b

No Duplicated Branches


Having two cases in a switch statement or two branches in an if chain with the same implementation is at best duplicate code, and at worst a coding error. If the same logic is truly needed for both instances, then in an if chain they should be combined, or for a switch, one should fall through to the other.

https://github.com/SonarSource/eslint-plugin-sonarjs/blob/HEAD/docs/rules/no-duplicated-branches.md

👍 Examples of correct code

switch (i) {
  case 1:
  case 3:
    doFirstThing();
    doSomething();
    break;
  case 2:
    doSomethingDifferent();
    break;
  default:
    doTheRest();
}

if ((a >= 0 && a < 10) || (a >= 20 && a < 50)) {
  doFirstThing();
  doTheThing();
} else if (a >= 10 && a < 20) {
  doTheOtherThing();
} else {
  doTheRest();
}

// Or

switch (i) {
  case 1:
    doFirstThing();
    doSomething();
    break;
  case 2:
    doSomethingDifferent();
    break;
  case 3:
    doFirstThing();
    doThirdThing();
    break;
  default:
    doTheRest();
}

if (a >= 0 && a < 10) {
  doFirstThing();
  doTheThing();
} else if (a >= 10 && a < 20) {
  doTheOtherThing();
} else if (a >= 20 && a < 50) {
  doFirstThing();
  doTheThirdThing();
} else {
  doTheRest();
}

👎 Examples of incorrect code

switch (i) {
  case 1:
    doFirstThing();
    doSomething();
    break;
  case 2:
    doSomethingDifferent();
    break;
  case 3: // Noncompliant; duplicates case 1's implementation
    doFirstThing();
    doSomething();
    break;
  default:
    doTheRest();
}

if (a >= 0 && a < 10) {
  doFirstThing();
  doTheThing();
} else if (a >= 10 && a < 20) {
  doTheOtherThing();
} else if (a >= 20 && a < 50) {
  // Noncompliant; duplicates first condition
  doFirstThing();
  doTheThing();
} else {
  doTheRest();
}

No Identical Functions


When two functions have the same implementation, either it was a mistake - something else was intended - or the duplication was intentional, but may be confusing to maintainers. In the latter case, the code should be refactored.

https://github.com/SonarSource/eslint-plugin-sonarjs/blob/HEAD/docs/rules/no-identical-functions.md

👍 Examples of correct code

function calculateCode() {
  doTheThing();
  doOtherThing();
  return code;
}

function getName() {
  return calculateCode();
}

👎 Examples of incorrect code

function calculateCode() {
  doTheThing();
  doOtherThing();
  return code;
}

function getName() { // Noncompliant
  doTheThing();
  doOtherThing();
  return code;
}

No Inverted Boolean Check


It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead.

https://github.com/SonarSource/eslint-plugin-sonarjs/blob/HEAD/docs/rules/no-inverted-boolean-check.md

👍 Examples of correct code

if (a !== 2) { ... }

👎 Examples of incorrect code

if (!(a === 2)) { ... }  // Noncompliant

No Nested Switch


Nested switch structures are difficult to understand because you can easily confuse the cases of an inner switch as belonging to an outer statement. Therefore nested switch statements should be avoided.

https://github.com/SonarSource/eslint-plugin-sonarjs/blob/HEAD/docs/rules/no-nested-switch.md

👍 Examples of correct code

function foo(n, m) {
  switch (n) {
    case 0:
      return bar(m);
    case 1:
      // ...
    default:
      // ...
  }
}

function bar(m) {
  switch(m) {
    // ...
  }
}

👎 Examples of incorrect code

function foo(n, m) {
  switch (n) {
    case 0:
      switch (m) {  // Noncompliant; nested switch
        // ...
      }
    case 1:
      // ...
    default:
      // ...
  }
}

No Nested Template Literals


Template literals (previously named "template strings") are an elegant way to build a string without using the + operator to make strings concatenation more readable.

https://github.com/SonarSource/eslint-plugin-sonarjs/blob/HEAD/docs/rules/no-nested-template-literals.md

👍 Examples of correct code

let color = "red";
let count = 3;
let apples = color ? `${count} ${color}` : count;
let message = `I have ${apples} apples`;

👎 Examples of incorrect code

let color = "red";
let count = 3;
let message = `I have ${color ? `${count} ${color}` : count} apples`;

No Redundant Boolean


Redundant Boolean literals should be removed from expressions to improve readability.

https://github.com/SonarSource/eslint-plugin-sonarjs/blob/HEAD/docs/rules/no-redundant-boolean.md

👍 Examples of correct code

if (booleanMethod()) { /* ... */ }
if (!booleanMethod()) { /* ... */ }
if (booleanMethod()) { /* ... */ }
doSomething(true);
doSomething(booleanMethod());

👎 Examples of incorrect code

if (booleanMethod() == true) { /* ... */ }
if (booleanMethod() == false) { /* ... */ }
if (booleanMethod() || false) { /* ... */ }
doSomething(!false);
doSomething(booleanMethod() == true);

Prefer Immediate Return


Declaring a variable only to immediately return or throw it is a bad practice.

https://github.com/SonarSource/eslint-plugin-sonarjs/blob/HEAD/docs/rules/prefer-immediate-return.md

👍 Examples of correct code

function ms(hours, minutes, seconds) {
  return ((hours * 60 + minutes) * 60 + seconds) * 1000;
}

👎 Examples of incorrect code

function ms(hours, minutes, seconds) {
  const duration = ((hours * 60 + minutes) * 60 + seconds) * 1000;

  return duration;
}

Prefer Object Literal


Object literal syntax, which initializes an object's properties inside the object declaration is cleaner and clearer than the alternative: creating an empty object, and then giving it properties one by one.

https://github.com/SonarSource/eslint-plugin-sonarjs/blob/HEAD/docs/rules/prefer-object-literal.md

👍 Examples of correct code

var person = {
  firstName: "John",
  middleInitial: "Q",
  lastName: "Public",
};

👎 Examples of incorrect code

var person = {}; // Noncompliant
person.firstName = "John";
person.middleInitial = "Q";
person.lastName = "Public";

Prefer Single Boolean Return


Return of boolean literal statements wrapped into if-then-else flow should be simplified.

https://github.com/SonarSource/eslint-plugin-sonarjs/blob/HEAD/docs/rules/prefer-single-boolean-return.md

👍 Examples of correct code

return expression;

👎 Examples of incorrect code

if (expression) {
  return true;
} else {
  return false;
}

// or

if (expression) {
  return true;
}
return false;

No Shadow


Enforces placing object properties on separate lines.

Then any code used within the same scope would not get the global undefined, but rather the local version with a very different meaning.

https://eslint.org/docs/rules/no-shadow https://eslint.org/docs/rules/no-shadow-restricted-names https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-shadow.md https://sonarsource.github.io/rspec/#/rspec/S1527/javascript

👍 Examples of correct code

var a = 3;
function b() {
    var c = 10;
}

var b = function () {
    var c = 10;
}

function b(a) {
    var c = 10;
}
b(a);

function f(a, b){}

var elements = document.getElementsByName("foo"); // Compliant
var someData = { package: true };                 // Compliant, as it is not used as an identifier here

👎 Examples of incorrect code

var a = 3;
function b() {
    var a = 10;
}

var b = function () {
    var a = 10;
}

function b(a) {
    a = 10;
}
b(a);

if (true) {
    let a = 5;
}

function NaN(){}

!function(Infinity){};

var undefined = 5;

try {} catch(eval){}

var package = document.getElementsByName("foo"); // Noncompliant

Parentheses New Line


This rule enforces consistent line breaks inside parentheses of function parameters or arguments.

https://eslint.org/docs/latest/rules/function-paren-newline https://eslint.org/docs/latest/rules/function-call-argument-newline

👍 Examples of correct code

function foo(
  bar,
  baz
) {}

var foo = function(bar, baz) {};

var foo = (
  bar
) => {};

foo(
  function() {
    return baz;
  }
);

foo("one", "two", "three");
// or
foo(
    "one",
    "two",
    "three"
);

bar("one", "two", {
    one: 1,
    two: 2
});
// or
bar(
    "one",
    "two",
    { one: 1, two: 2 }
);
// or
bar(
    "one",
    "two",
    {
        one: 1,
        two: 2
    }
);

baz("one", "two", (x) => {
    console.log(x);
});
// or
baz(
    "one",
    "two",
    (x) => {
        console.log(x);
    }
);

👎 Examples of incorrect code

function foo(bar,
  baz
) {}

var foo = function(bar,
baz) {};

var foo = (
  bar) => {};

foo(
  function() {
    return baz;
  });

foo("one", "two",
    "three");
//or
foo("one",
    "two", "three");

bar("one", "two",
    { one: 1, two: 2}
);

baz("one", "two",
    (x) => { console.log(x); }
);

No Func Call Spacing


Disallows space between the function name and the opening parenthesis.

https://eslint.org/docs/latest/rules/func-call-spacing

👍 Examples of correct code

fn();

👎 Examples of incorrect code

fn ();

fn
();

Array Element New Line


This rule enforces line breaks between array elements.

https://eslint.org/docs/latest/rules/array-element-newline

👍 Examples of correct code

var a = [];
var b = [1];
var c = [1, 2];
var d = [1, 2, 3];
var e = [
    1,
    2
];
var f = [
    1,
    2,
    3
];
var g = [
    function foo() {
        dosomething();
    }, function bar() {
        dosomething();
    }, function baz() {
        dosomething();
    }
];
var h = [
    function foo() {
        dosomething();
    },
    function bar() {
        dosomething();
    },
    function baz() {
        dosomething();
    }
];

👎 Examples of incorrect code

var a = [
    1, 2,
    3
];
var b = [
    function foo() {
        dosomething();
    }, function bar() {
        dosomething();
    },
    function baz() {
        dosomething();
    }
];

Wrap Iife


Enforces always wrapping the function expression

https://eslint.org/docs/latest/rules/wrap-iife

👍 Examples of correct code

var x = (function () { return { y: 1 }; })(); // wrapped function expression

👎 Examples of incorrect code

var x = function () { return { y: 1 };}(); // unwrapped
var x = (function () { return { y: 1 };}()); // wrapped call expression

Disallow Template Tag Space


Disallows spaces between a tag function and its template literal.

https://eslint.org/docs/latest/rules/template-tag-spacing

👍 Examples of correct code

func`Hello world`;

👎 Examples of incorrect code

func `Hello world`;

No Space Spread


Enforce spacing between rest and spread operators and their expressions

https://eslint.org/docs/latest/rules/rest-spread-spacing

👍 Examples of correct code

fn(...args)
[...arr, 4, 5, 6]
let [a, b, ...arr] = [1, 2, 3, 4, 5];
function fn(...args) { console.log(args); }
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
let n = { x, y, ...z };

👎 Examples of incorrect code

fn(... args)
[... arr, 4, 5, 6]
let [a, b, ... arr] = [1, 2, 3, 4, 5];
function fn(... args) { console.log(args); }
let { x, y, ... z } = { x: 1, y: 2, a: 3, b: 4 };
let n = { x, y, ... z };

Inline IF


Disallows a newline before a single-line statement.

https://eslint.org/docs/latest/rules/nonblock-statement-body-position

👍 Examples of correct code

if (foo) bar();
else baz();

while (foo) bar();

for (let i = 1; i < foo; i++) bar();

do bar(); while (foo)

if (foo) { // block statements are always allowed with this rule
  bar();
} else {
  baz();
}

👎 Examples of incorrect code

if (foo)
  bar();
else
  baz();

while (foo)
  bar();

for (let i = 1; i < foo; i++)
  bar();

do
  bar();
while (foo)

New Instance Use Parentheses


This rule can enforce or disallow parentheses when invoking a constructor with no arguments using the new keyword.

https://eslint.org/docs/latest/rules/new-parens

👍 Examples of correct code

var person = new Person();
var person = new Person("name");

👎 Examples of incorrect code

var person = new Person;
var person = new (Person);

Logical Assignment Operators


The shorthand can be used if the assignment target and the left expression of a logical expression are the same. For example a = a || b can be shortened to a ||= b.

https://eslint.org/docs/latest/rules/logical-assignment-operators

👍 Examples of correct code

a = b
a += b
a ||= b
a = b || c
a || (b = c)

if (a) a = b

👎 Examples of incorrect code

a = a || b
a = a && b
a = a ?? b
a || (a = b)
a && (a = b)
a ?? (a = b)

No With


The with statement is potentially problematic because it adds members of an object to the current scope, making it impossible to tell what a variable inside the block actually refers to.

https://eslint.org/docs/rules/no-with

👍 Examples of correct code

const r = ({x, y}) => Math.sqrt(x * x + y * y);

👎 Examples of incorrect code

with (point) {
    r = Math.sqrt(x * x + y * y); // is r a member of point?
}

Promise Rules

No New Statics


Calling a Promise static method with new is invalid, resulting in a TypeError at runtime.

https://github.com/xjamundx/eslint-plugin-promise/blob/development/docs/rules/no-new-statics.md

👍 Examples of correct code

Promise.resolve(value)
Promise.reject(error)
Promise.race([p1, p2])
Promise.all([p1, p2])

👎 Examples of incorrect code

new Promise.resolve(value)
new Promise.reject(error)
new Promise.race([p1, p2])
new Promise.all([p1, p2])

No Return Wrap


Ensure that inside a then() or a catch() we always return or throw a raw value instead of wrapping in Promise.resolve or Promise.reject

https://github.com/xjamundx/eslint-plugin-promise/blob/development/docs/rules/no-new-statics.md

👍 Examples of correct code

myPromise.then(function (val) {
  return val * 2
})
myPromise.then(function (val) {
  throw new Exception("Message");
})

👎 Examples of incorrect code

myPromise.then(function (val) {
  return Promise.resolve(val * 2)
})
myPromise.then(function (val) {
  return Promise.reject('bad thing')
})

Param Name


Ensure that inside a then() or a catch() we always return or throw a raw value instead of wrapping in Promise.resolve or Promise.reject

https://github.com/xjamundx/eslint-plugin-promise/blob/development/docs/rules/param-names.md

👍 Examples of correct code

new Promise(function (resolve) { ... })
new Promise(function (resolve, reject) { ... })
new Promise(function (_resolve, _reject) { ... }) // Unused marker for parameters are allowed

👎 Examples of incorrect code

new Promise(function (reject, resolve) { ... }) // incorrect order
new Promise(function (ok, fail) { ... }) // non-standard parameter names
new Promise(function (_, reject) { ... }) // a simple underscore is not allowed

Always Return


Ensure that inside a then() or a catch() we always return or throw a raw value instead of wrapping in Promise.resolve or Promise.reject

https://github.com/xjamundx/eslint-plugin-promise/blob/development/docs/rules/always-return.md

👍 Examples of correct code

myPromise.then((val) => val * 2);
myPromise.then(function(val) { return val * 2; });
myPromise.then(doSomething); // could be either
myPromise.then((b) => { if (b) { return "yes" } else { return "no" } });

👎 Examples of incorrect code

myPromise.then(function (val) {})
myPromise.then(() => {
  doSomething()
})
myPromise.then((b) => {
  if (b) {
    return 'yes'
  } else {
    forgotToReturn()
  }
})

No Nesting


Warning Avoid nested then() or catch() statements (no-nesting)

https://github.com/xjamundx/eslint-plugin-promise/blob/development/docs/rules/no-nesting.md

👍 Examples of correct code

myPromise.then(doSomething).then(doSomethingElse).catch(errors)

👎 Examples of incorrect code

myPromise.then((val) => doSomething(val).then(doSomethingElse))

myPromise.then((val) => doSomething(val).catch(errors))

myPromise.catch((err) => doSomething(err).then(doSomethingElse))

myPromise.catch((err) => doSomething(err).catch(errors))

No Return Finally


Disallow return statements inside a callback passed to finally(), since nothing would consume what's returned.

https://github.com/xjamundx/eslint-plugin-promise/blob/development/docs/rules/no-return-in-finally.md

👍 Examples of correct code

myPromise.finally(function (val) {
  console.log('value:', val)
})

👎 Examples of incorrect code

myPromise.finally(function (val) {
  return val
})

Valid Params


Disallow return statements inside a callback passed to finally(), since nothing would consume what's returned.

https://github.com/xjamundx/eslint-plugin-promise/blob/development/docs/rules/valid-params.md

👍 Examples of correct code

// Promise.all() requires 1 argument
Promise.all([p1, p2, p3])
Promise.all(iterable)

// Promise.race() requires 1 argument
Promise.race([p1, p2, p3])
Promise.race(iterable)

// Promise.resolve() requires 0 or 1 arguments
Promise.resolve()
Promise.resolve({})
Promise.resolve([1, 2, 3])
Promise.resolve(referenceToObject)

// Promise.reject() requires 0 or 1 arguments
Promise.reject()
Promise.reject(Error())
Promise.reject(referenceToError)

// Promise.then() requires 1 or 2 arguments
somePromise().then((value) => doSomething(value))
somePromise().then(successCallback, errorCallback)

// Promise.catch() requires 1 argument
somePromise().catch((error) => {
  handleError(error)
})
somePromise().catch(console.error)

// Promise.finally() requires 1 argument
somePromise().finally(() => {
  console.log('done!')
})
somePromise().finally(console.log)

👎 Examples of incorrect code

Promise.all() // is called with 0 or 2+ arguments
Promise.race() // is called with 0 or 2+ arguments
Promise.resolve(a, b) // is called with 2+ arguments
Promise.reject(a, b) // is called with 2+ arguments
Promise.then() // is called with 0 or 3+ arguments
Promise.catch() // is called with 0 or 2+ arguments
Promise.finally() // is called with 0 or 2+ arguments

No Async Promise Executor


Disallows using an async function as a Promise executor.

https://eslint.org/docs/rules/no-async-promise-executor

👍 Examples of correct code

const foo = new Promise((resolve, reject) => {
  readFile('foo.txt', function(err, result) {
    if (err) {
      reject(err);
    } else {
      resolve(result);
    }
  });
});

const result = Promise.resolve(foo);

👎 Examples of incorrect code

const foo = new Promise(async (resolve, reject) => {
  readFile('foo.txt', function(err, result) {
    if (err) {
      reject(err);
    } else {
      resolve(result);
    }
  });
});

const result = new Promise(async (resolve, reject) => {
  resolve(await foo);
});

No Misused Promises


Block misused of promise

https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-misused-promises.md

👍 Examples of correct code

const promise = Promise.resolve('value');

// Always `await` the Promise in a conditional
if (await promise) {
  // Do something
}

const val = (await promise) ? 123 : 456;

while (await promise) {
  // Do something
}

👎 Examples of incorrect code

const promise = Promise.resolve('value');

// always true
if (promise) {
  // Do something
}

const val = promise ? 123 : 456;

while (promise) {
  // Do something
}

Import

New Line After Import


Enforces having one empty lines after the last top-level import statement or require call.

https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/newline-after-import.md

👍 Examples of correct code

import defaultExport from './foo'

const FOO = 'BAR'

// OR
import defaultExport from './foo'
import { bar }  from 'bar-lib'

const FOO = 'BAR'

// OR
const FOO = require('./foo')
const BAR = require('./bar')

const BAZ = 1

👎 Examples of incorrect code

import * as foo from 'foo'
const FOO = 'BAR'

// OR
import * as foo from 'foo'
const FOO = 'BAR'

import { bar }  from 'bar-lib'

// OR
const FOO = require('./foo')
const BAZ = 1
const BAR = require('./bar')

Import Deprecated


Reports use of a deprecated name, as indicated by a JSDoc block with a @deprecated tag or TomDoc Deprecated: comment.

https://github.com/import-js/eslint-plugin-import/blob/HEAD/docs/rules/no-deprecated.md

👍 Examples of correct code

👎 Examples of incorrect code

// @file: ./answer.js

/**
 * this is what you get when you trust a mouse talk show
 * @deprecated need to restart the experiment
 * @returns {Number} nonsense
 */
export function multiply(six, nine) {
  return 42
}

import { multiply } from './answer';

No Mutable Export


Forbids the use of mutable exports with var or let.

https://github.com/import-js/eslint-plugin-import/blob/HEAD/docs/rules/no-mutable-exports.md

👍 Examples of correct code

export const count = 1
export function getCount() {}
export class Counter {}

👎 Examples of incorrect code

export let count = 2
export var count = 3

let count = 4
export { count } // reported here

No Amd


Reports require([array], ...) and define([array], ...) function calls at the module scope.

https://github.com/import-js/eslint-plugin-import/blob/HEAD/docs/rules/no-amd.md

👍 Examples of correct code

👎 Examples of incorrect code

define(["a", "b"], function (a, b) { /* ... */ })

require(["b", "c"], function (b, c) { /* ... */ })

Prefer Default Export


When there is only a single export from a module, prefer using default export over named export.

https://github.com/import-js/eslint-plugin-import/blob/HEAD/docs/rules/prefer-default-export.md

👍 Examples of correct code

// There is a default export.
export const foo = 'foo';
const bar = 'bar';
export default bar;

// or

// good2.js
// There is more than one named export in the module.
export const foo = 'foo';
export const bar = 'bar';

// or

// good3.js
// There is more than one named export in the module
const foo = 'foo';
const bar = 'bar';
export { foo, bar }

// or

// good4.js
// There is a default export.
const foo = 'foo';
export { foo as default }

// or

// export-star.js
// Any batch export will disable this rule. The remote module is not inspected.
export * from './other-module'

👎 Examples of incorrect code

// There is only a single module export and it's a named export.
export const foo = 'foo';

Max Imports


Forbid modules to have too many dependencies (import or require statements).

https://github.com/import-js/eslint-plugin-import/blob/HEAD/docs/rules/max-dependencies.md

👍 Examples of correct code

import a from './a'; // 1
const b = require('./b'); // 2
// ...
import y from './y'; // 25 - No exceeds!

👎 Examples of incorrect code

import a from './a'; // 1
const b = require('./b'); // 2
// ...
import z from './z'; // 26 - exceeds max!

No CommanJs Export


Reports the use of import declarations with CommonJS exports in any module except for the main module.

https://github.com/import-js/eslint-plugin-import/blob/HEAD/docs/rules/no-import-module-exports.md

👍 Examples of correct code

import thing from 'other-thing'
export default thing

const thing = require('thing')
module.exports = thing

const thing = require('thing')
exports.foo = bar

import thing from 'otherthing'
console.log(thing.module.exports)

// in lib/index.js
import foo from 'path';
module.exports = foo;

👎 Examples of incorrect code

import { stuff } from 'starwars'
module.exports = thing

import * as allThings from 'starwars'
exports.bar = thing

import thing from 'other-thing'
exports.foo = bar

import thing from 'starwars'
const baz = module.exports = thing
console.log(baz)

No Useless Path Import


Use this rule to prevent unnecessary path segments in import and require statements.

https://github.com/import-js/eslint-plugin-import/blob/HEAD/docs/rules/no-useless-path-segments.md

👍 Examples of correct code

import "./header.js";
import "./pages";
import "./pages/about";
import ".";
import "..";
import fs from "fs";

👎 Examples of incorrect code

import "./../my-project/pages/about.js"; // should be "./pages/about.js"
import "./../my-project/pages/about"; // should be "./pages/about"
import "../my-project/pages/about.js"; // should be "./pages/about.js"
import "../my-project/pages/about"; // should be "./pages/about"
import "./pages//about"; // should be "./pages/about"
import "./pages/"; // should be "./pages"
import "./pages/index"; // should be "./pages" (except if there is a ./pages.js file)
import "./pages/index.js"; // should be "./pages" (except if there is a ./pages.js file)

No Extraneous Dependencies


Disable import dependencies if no exists in package.json dependencies

https://github.com/import-js/eslint-plugin-import/blob/HEAD/docs/rules/no-extraneous-dependencies.md

👍 Examples of correct code

import anything from "anything"; // exists in dependencies

👎 Examples of incorrect code

import typescript from "typescript"; // exists in dev dependency package.json

Import Order


Enforce a convention in the order of require() / import statements Use: Alphabetic order import

https://github.com/import-js/eslint-plugin-import/blob/HEAD/docs/rules/order.md

👍 Examples of correct code

import fs from "fs"
import file from "./file";
import file2 from "./file2";

👎 Examples of incorrect code

import file from "./file";
import fs from "fs"
import file2 from "./file2";

No Anonymous Default Export


Reports if a module's default export is unnamed.

https://github.com/import-js/eslint-plugin-import/blob/HEAD/docs/rules/no-anonymous-default-export.md

👍 Examples of correct code

const foo = 123;
export default foo;

export default class MyClass() {};

export default function foo() {};

👎 Examples of incorrect code

export default []

export default () => {}

export default class {}

export default function () {}

export default 123

export default {}

export default new Foo()

Prefer Node Protocol


Prefer using the node: protocol when importing Node.js builtin modules

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-node-protocol.md

👍 Examples of correct code

import dgram from 'node:dgram';
export {strict as default} from 'node:assert';
import fs from 'node:fs/promises';
const fs = require('fs');
import _ from 'lodash';
import fs from './fs.js';
const fs = require('node:fs/promises');

👎 Examples of incorrect code

import dgram from 'dgram';
export {strict as default} from 'assert';
import fs from 'fs/promises';
const fs = require('fs/promises');

Prefer export from


Prefer export…from when re-exporting

When re-exporting from a module, it's unnecessary to import and then export. It can be done in a single export…from declaration.

https://github.com/sindresorhus/eslint-plugin-unicorn/blob/main/docs/rules/prefer-export-from.md

👍 Examples of correct code

export {default} from './foo.js';

export {named} from './foo.js';

export * as namespace from './foo.js';
export {
    default,
    default as renamedDefault,
    named,
    named as renamedNamed,
} from './foo.js';

// There is no substitution
import * as namespace from './foo.js';
export default namespace;

👎 Examples of incorrect code

import defaultExport from './foo.js';
export default defaultExport;

import {named} from './foo.js';
export {named};

import * as namespace from './foo.js';
export {namespace};

import defaultExport, {named} from './foo.js';
export default defaultExport;
export {
    defaultExport as renamedDefault,
    named,
    named as renamedNamed,
};

No Empty Import


Prevent import empty

https://github.com/ODGodinho/ODG-Linter-Js

👍 Examples of correct code

import { a } from './foo.js';
import a from './foo.js';

👎 Examples of incorrect code

import { } from './foo.js';
import t, { } from './foo.js';
import type { } from './foo.js';

Export End File


Ensure all exports appear after other statements.

https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/exports-last.md

👍 Examples of correct code

import { a } from './foo.js';
import a from './foo.js';

👎 Examples of incorrect code

import { } from './foo.js';
import t, { } from './foo.js';

Import First


This rule reports any imports that come after non-import statements.

https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/first.md

👍 Examples of correct code

import foo from './foo'
import bar from './bar' // <- reported

initWith(foo)

👎 Examples of incorrect code

import foo from './foo'

// some module-level initializer
initWith(foo)

import bar from './bar' // <- reported

No Named Default


Reports use of a default export as a locally named import.

https://github.com/import-js/eslint-plugin-import/blob/main/docs/rules/no-named-default.md

👍 Examples of correct code

import foo from './foo.js';
import foo, { bar } from './foo.js';

👎 Examples of incorrect code

// message: Using exported name 'bar' as identifier for default export.
import { default as foo } from './foo.js';
import { default as foo, bar } from './foo.js';

Documentation

Spaced Comment


Require space after comment block.

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.

https://eslint.org/docs/rules/spaced-comment https://eslint.org/docs/latest/rules/lines-around-comment

👍 Examples of correct code

// This is a comment with a whitespace at the beginning

/* This is a comment with a whitespace at the beginning */

/*
 * This is a comment with a whitespace at the beginning
 */

/**
 * valid
 */
function() {}

👎 Examples of incorrect code

//This is a comment with no whitespace at the beginning

/*This is a comment with no whitespace at the beginning */

/**
 * invalid after space
 */

function() {}

Capitalized Comments


Require capitalization of the first letter of a comment.

https://eslint.org/docs/rules/capitalized-comments

👍 Examples of correct code

// Capitalized comment

// 1. Non-letter at beginning of comment

// 丈 Non-Latin character at beginning of comment

👎 Examples of incorrect code

// lowercase comment

Comment Align


Require alignment of JSDoc block asterisks.

https://github.com/gajus/eslint-plugin-jsdoc#user-content-eslint-plugin-jsdoc-rules-check-alignment

👍 Examples of correct code

/**
 * @param {Number} foo
 */

👎 Examples of incorrect code

/**
  * @param {Number} foo
 */

/**
* @param {Number} foo
*/

Disallow Space Align


Disallow use space for align dockblock

https://github.com/gajus/eslint-plugin-jsdoc#user-content-eslint-plugin-jsdoc-rules-check-alignment

👍 Examples of correct code

/**
 * @param {string} lorem Description.
 * @param {int} sit Description multi words.
 */

👎 Examples of incorrect code

/**
 * @param {string} lorem Description.
 * @param {int}    sit Description multi words.
 */

Validate Param


Check is valid @param and exists

https://github.com/gajus/eslint-plugin-jsdoc#check-param-names

👍 Examples of correct code

/**
 * @param {string} a Description.
 */
foo(a) {
}

/**
 * @param {string} a Description.
 * @param {string} b Description.
 */
foo(a, b) {
}

👎 Examples of incorrect code

/**
 * @param {string} b B iss not exists.
 */
foo(a) {
}

/**
 * @param {string} b order is not correct
 * @param {string} a
 */
foo(a, b) {
}

/**
 * @param {string} a
 * required b
 */
foo(a, b) {
}

Validate Syntax


Check is valid syntax docblock

https://github.com/gajus/eslint-plugin-jsdoc#check-syntax

👍 Examples of correct code

/**
 * @param {string} foo
 */
function quux (foo) {

}

👎 Examples of incorrect code

/**
 * @param {string=} foo
 */
function quux (foo) {

}

/**
 * @param {string} [foo]
 */
function quux (foo) {

}

Validate Tag Name


Check is valid tag docblock

https://github.com/gajus/eslint-plugin-jsdoc#check-tag-names

👍 Examples of correct code

/**
 * @param
 */

👎 Examples of incorrect code

/**
 * @notExistTag
 */

Validate Types


Check is valid type in docblock

https://github.com/gajus/eslint-plugin-jsdoc#check-types

👍 Examples of correct code

/**
 * @param {string} a
 */

👎 Examples of incorrect code

/**
 * @param {strings} a strings is not valid
 */

Validate Values


Check is valid values in docblock

https://github.com/gajus/eslint-plugin-jsdoc#check-values

👍 Examples of correct code

/**
 * @version 1.0.0
 */

/**
 * @version v1.0.0
 */

👎 Examples of incorrect code

/**
 * @version v 1.0.0
 */

/**
 * @version it's my version
 */

Empty Tags


Require tags is empty

https://github.com/gajus/eslint-plugin-jsdoc#user-content-eslint-plugin-jsdoc-rules-empty-tags

👍 Examples of correct code

/**
 * @global
 */

👎 Examples of incorrect code

/**
 * @global this is global
 */

Disallow Extra Asterisk


Disallow Extra asterisk in docblock

https://github.com/gajus/eslint-plugin-jsdoc#no-multi-asterisks

👍 Examples of correct code

/**
 * bold text
 */

👎 Examples of incorrect code

/**
 * *bold* text
 */

Disallow Default Value


Disallow Extra asterisk in docblock

https://github.com/gajus/eslint-plugin-jsdoc#user-content-eslint-plugin-jsdoc-rules-no-defaults

👍 Examples of correct code

/**
 * @param {number} foo
 */
function quux(foo) {

}

👎 Examples of incorrect code

/**
 * @param {number} [foo="7"]
 */
function quux(foo) {

}

Regex Rules

No Optional With Assertion


This rule reports elements that contradict an assertion. All elements reported by this rule fall into one of two categories:

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-contradiction-with-assertion.html

👍 Examples of correct code

var foo = /a\b-a/;
var foo = /a\ba/; // handled by regexp/no-useless-assertions

👎 Examples of incorrect code

var foo = /a\b-?a/;
var foo = /a\b(a|-)/;
var foo = /a\ba*-/;

No Control Character


Control characters are special, invisible characters in the ASCII range 0-31. These characters are rarely used in JavaScript strings so a regular expression containing elements that explicitly match these characters is most likely a mistake.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-control-character.html

👍 Examples of correct code

var foo = /\n/;
var foo = RegExp("\n");

var pattern1 = /\x20/;
var pattern2 = /\u0020/;
var pattern3 = /\u{20}/u;
var pattern4 = /\t/;
var pattern5 = /\n/;
var pattern6 = new RegExp("\x20");
var pattern7 = new RegExp("\\t");
var pattern8 = new RegExp("\\n");

👎 Examples of incorrect code

var foo = /\x1f/;
var foo = /\x0a/;
var foo = RegExp('\x0a');

var pattern1 = /\x00/;
var pattern2 = /\x0C/;
var pattern3 = /\x1F/;
var pattern4 = /\u000C/;
var pattern5 = /\u{C}/u;
var pattern6 = new RegExp("\x0C"); // raw U+000C character in the pattern
var pattern7 = new RegExp("\\x0C"); // \x0C pattern

No Dupe Condition


This rule disallows duplicate disjunctions.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-dupe-disjunctions.html

👍 Examples of correct code

const foo = /a|b/
const foo = /(a|b)/
const foo = /(?:a|b)/

👎 Examples of incorrect code

const foo = /a|a/
const foo = /(a|a)/
const foo = /(?:a|a)/
const foo = /abc|abc/
const foo = /[ab]|[ba]/
const foo = /a|abc/
const foo = /.|abc/
const foo = /.|a|b|c/

No Empty Alternative


While (re-)writing long regular expressions, it can happen that one forgets to remove the | character of a former alternative. This rule tries to point out these potential mistakes by reporting all empty alternatives.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-empty-alternative.html

👍 Examples of correct code

var foo = /(?:)/
var foo = /a+|b*/

👎 Examples of incorrect code

var foo = /a+|b+|/
var foo = /\|\||\|||\|\|\|/
var foo = /a(?:a|bc|def|h||ij|k)/

No Empty Capturing Group


This rule reports capturing group that captures assertions.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-empty-capturing-group.html

👍 Examples of correct code

var foo = /(?:)/
var foo = /a+|b*/

👎 Examples of incorrect code

var foo = /a+|b+|/
var foo = /\|\||\|||\|\|\|/
var foo = /a(?:a|bc|def|h||ij|k)/

No Empty Character Class


This rule reports character classes that cannot match any characters.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-empty-character-class.html

👍 Examples of correct code

var foo = /abc[d]/;
var foo = /abc[a-z]/;
var foo = /[^]/;
var foo = /[\s\S]/;

👎 Examples of incorrect code

var foo = /abc[]/;
var foo = /[^\s\S]/;

No Empty Group


This rule reports empty groups.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-empty-group.html

👍 Examples of correct code

var foo = /(a)/;
var foo = /(?:a)/;

👎 Examples of incorrect code

var foo = /()/;
var foo = /(|)/;
// non-capturing group
var foo = /(?:)/;
var foo = /(?:|)/;

No Empty Look Rounds Assertion


This rule reports empty lookahead assertion or empty lookbehind assertion.

What are empty look around?

An empty look around is a look around for which at least one path in the look around expression contains only elements that do not consume characters and do not assert characters. This means that the look around expression will trivially accept any input string.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-empty-lookarounds-assertion.html

👍 Examples of correct code

var foo = /x(?=y)/;
var foo = /x(?!y)/;
var foo = /(?<=y)x/;
var foo = /(?<!y)x/;

👎 Examples of incorrect code

var foo = /x(?=)/;
var foo = /x(?!)/;
var foo = /(?<=)x/;
var foo = /(?<!)x/;
var foo = /(?=b?)\w/;
var foo = /(?!b?)\w/;

No Escape Backspace


This rule reports [\b]. The word boundaries (\b) and the escape backspace ([\b]) are indistinguishable at a glance. This rule does not allow backspace ([\b]). Use unicode escapes (\u0008) instead.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-escape-backspace.html

👍 Examples of correct code

var foo = /\b/;
var foo = /\u0008/;
var foo = /\cH/;
var foo = /\x08/;

👎 Examples of incorrect code

var foo = /[\b]/;

No Invalid Regexp


This rule reports invalid regular expression patterns given to RegExp constructors.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-invalid-regexp.html

👍 Examples of correct code

RegExp('foo')
RegExp('[a' + ']')

👎 Examples of incorrect code

RegExp('\\')
RegExp('[a-Z]*')
RegExp('\\p{Foo}', 'u')

const space = '\\s*'
RegExp('=' + space + '+(\\w+)', 'u')

No Lazy Ends


If a lazily quantified element is the last element matched by an expression (e.g. the a{2,3}? in b+a{2,3}?), we know that the lazy quantifier will always only match the element the minimum number of times. The maximum is completely ignored because the expression can accept after the minimum was reached.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-lazy-ends.html

👍 Examples of correct code

var foo = /a+?b*/.test(str)
var foo = /a??(?:ba+?|c)*/.test(str)
var foo = /ba*?$/.test(str)

👎 Examples of incorrect code

var foo = /a??/.test(str)
var foo = /a+b+?/.test(str)
var foo = /a(?:c|ab+?)?/.test(str)

No Misleading Unicode Character


This rule reports misleading Unicode characters.

Some Unicode characters like '❇️', '🇧🇷', and '👨‍👩‍👦' consist of multiple code points. This causes problems in character classes and around quantifiers. E.g.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-misleading-unicode-character.html

👍 Examples of correct code

var foo = /👍+/u;
var foo = /👨‍👩‍👦/;

👎 Examples of incorrect code

var foo = /👍+/;
var foo = /[❇️👨‍👩‍👦]❤️/;

No Optional Assertion


Assertions that are quantified (directly or indirectly) can be considered optional if the quantifier has a minimum of zero.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-optional-assertion.html

👍 Examples of correct code

var foo = /\w+(?::|\b)/;

👎 Examples of incorrect code

var foo = /a(?:$)*b/;
var foo = /a(?:foo|(?<!-)(?:-|\b))*b/; // The `\b` is optional.
var foo = /(?:^)?\w+/;   // warns about `^`
var foo = /\w+(?::|$)?/; // warns about `$`

No Potentially Useless Back Reference


If the referenced group of a backreference is not matched because some other path leads to the back-reference, the back-reference will trivially accept (e.g. /(?:(a)|b)\1/). The same will happen if the captured text of the referenced group was reset before reaching the back-reference.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-potentially-useless-backreference.html https://eslint.org/docs/latest/rules/no-useless-backreference

👍 Examples of correct code

var foo = /(a+)b\1/;
var foo = /(a+)b|\1/;

👎 Examples of incorrect code

var foo = /(?:(a)|b)\1/;
var foo = /(a)?b\1/;
var foo = /((a)|c)+b\2/;

No Useless Assertions


Some assertion are unnecessary because the rest of the pattern forces them to always be accept (or reject).

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-useless-assertions.html

👍 Examples of correct code

var foo = /\bfoo\b/;

👎 Examples of incorrect code

var foo = /#\bfoo/;    // \b will always accept
var foo = /foo\bbar/;  // \b will always reject
var foo = /$foo/;      // $ will always reject
var foo = /(?=\w)\d+/; // (?=\w) will always accept

No Useless Back Reference


Back references that will always trivially accept serve no function and can be removed.

This rule is a based on the ESLint core no-useless-back-reference rule. It reports all the ESLint core rule reports and some more.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-useless-backreference.html

👍 Examples of correct code

var foo = /(a)b\1/;
var foo = /(a?)b\1/;
var foo = /(\b|a)+b\1/;
var foo = /(a)?(?:a|\1)/;

👎 Examples of incorrect code

var foo = /\1(a)/;
var foo = /(a\1)/;
var foo = /(a)|\1/;
var foo = /(?:(a)|\1)+/;
var foo = /(?<=(a)\1)/;
var foo = /(\b)a\1/;

No Useless Dollar Replacements


This rule aims to detect and disallow useless $ replacements in regular expression replacements.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-useless-dollar-replacements.html

👍 Examples of correct code

var newStr = str.replace(/(\w+)\s(\w+)/, '$2, $1');
// newStr = "Smith, John"

var newStr = str.replace(/(?<first>\w+)\s(?<last>\w+)/, '$<last>, $<first>');
// newStr = "Smith, John"

'123456789012'.replaceAll(/(.)../g, '$1**'); // "1**4**7**0**"

👎 Examples of incorrect code

var newStr = str.replace(/(\w+)\s(\w+)/, '$3, $1 $2');
// newStr = "$3, John Smith"

var newStr = str.replace(/(?<first>\w+)\s(?<last>\w+)/, '$<last>, $<first> $<middle>');
// newStr = "Smith, John "

var newStr = str.replace(/(\w+)\s(\w+)/, '$<last>, $<first>');
// newStr = "$<last>, $<first>"

Strict Regex


This rule disallows not strictly valid regular expressions.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/strict.html

👍 Examples of correct code

var foo = /\}/
var foo = /\{/
var foo = /\]/
var foo = /\u{42}/u; // It matches "B".
var foo = /u{42}/; // It matches a string followed by 42 "u"s.

👎 Examples of incorrect code

var foo = /}/
var foo = /{/
var foo = /]/
var foo = /\u{42}/; // It matches a string followed by 42 "u"s.

Confusing Quantifier


Confusing quantifiers are ones which imply one thing but don't deliver on that.

An example of this is (?:a?b*|c+){4}. The group is quantified with {4} which implies that at least 4 characters will be matched but this is not the case. The whole pattern will match the empty string. It does that because in the a?b* alternative, it's possible to choose 0 many a and b. So rather than {4}, {0,4} should be used to reflect the fact that the empty string can be matched.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/confusing-quantifier.html

👍 Examples of correct code

var foo = /a*/;
var foo = /(a|b|c)+/;
var foo = /a?/;

👎 Examples of incorrect code

var foo = /(a?){4}/; // warns about `{4}`
var foo = /(a?b*)+/; // warns about `+`

Control Character Escape


This rule reports control characters that were not escaped using a control escape (\0, t, \n, \v, f, \r).

https://ota-meshi.github.io/eslint-plugin-regexp/rules/control-character-escape.html

👍 Examples of correct code

var foo = /[\n\r]/;
var foo = /\t/;
var foo = RegExp("\t+\n");

👎 Examples of incorrect code

var foo = / /;
var foo = /\u0009/;
var foo = /\u{a}/u;
var foo = RegExp("\\u000a");

Negation


This rule enforces use of \D, \W, \S and \P on negation.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/negation.html

👍 Examples of correct code

var foo = /\D/
var foo = /\W/
var foo = /\S/
var foo = /\P{ASCII}/u

var foo = /\d/
var foo = /\w/
var foo = /\s/
var foo = /\p{ASCII}/u

👎 Examples of incorrect code

var foo = /[^\d]/
var foo = /[^\w]/
var foo = /[^\s]/
var foo = /[^\p{ASCII}]/u

var foo = /[^\D]/
var foo = /[^\W]/
var foo = /[^\S]/
var foo = /[^\P{ASCII}]/u

No Dupe Characters Character Class


Because multiple same character classes in regular expressions only one is useful, they might be typing mistakes.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-dupe-characters-character-class.html

👍 Examples of correct code

var foo = /[\(\)]/;

var foo = /[a-z\s]/;

var foo = /[\w]/;

👎 Examples of incorrect code

var foo = /[\\(\\)]/;
//          ^^ ^^        "\\" are duplicated
var foo = /[a-z\\s]/;
//          ^^^  ^       "s" are duplicated
var foo = /[\w0-9]/;
//          ^^^^^        "0-9" are duplicated

No Invisible Character


This rule disallows using invisible characters other than SPACE (U+0020) without using escapes.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-invisible-character.html

👍 Examples of correct code

var foo = /\t/;
var foo = /\v/;
var foo = /\f/;
var foo = /\u3000/;
var foo = / /; // SPACE (`U+0020`)

👎 Examples of incorrect code

// \u000B - Line Tabulation (\v) - <VT>
// \u000C - Form Feed (\f) - <FF>
// \u00A0 - No-Break Space - <NBSP>
// \u0085 - Next Line
// \u1680 - Ogham Space Mark
// \u180E - Mongolian Vowel Separator - <MVS>
// \ufeff - Zero Width No-Break Space - <BOM>
// \u2000 - En Quad
// \u2001 - Em Quad
// \u2002 - En Space - <ENSP>
// \u2003 - Em Space - <EMSP>
// \u2004 - Three-Per-Em
// \u2005 - Four-Per-Em
// \u2006 - Six-Per-Em
// \u2007 - Figure Space
// \u2008 - Punctuation Space - <PUNCSP>
// \u2009 - Thin Space
// \u200A - Hair Space
// \u200B - Zero Width Space - <ZWSP>
// \u2028 - Line Separator
// \u2029 - Paragraph Separator
// \u202F - Narrow No-Break Space
// \u205f - Medium Mathematical Space
// \u3000 - Ideographic Space

No Legacy Features


This rule disallow legacy RegExp features.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-legacy-features.html

👍 Examples of correct code

👎 Examples of incorrect code

RegExp.input
RegExp.$_
RegExp.lastMatch
RegExp["$&"]
RegExp.lastParen
RegExp["$+"]
RegExp.leftContext
RegExp["$`"]
RegExp.rightContext
RegExp["$'"]
RegExp.$1
RegExp.$2
RegExp.$3
RegExp.$4
RegExp.$5
RegExp.$6
RegExp.$7
RegExp.$8
RegExp.$9

const regexObj = new RegExp('foo', 'gi');
regexObj.compile('new foo', 'g');

No Non Standard Flag


This rule reports non-standard flags.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-non-standard-flag.html

👍 Examples of correct code

var foo = /a*b*c/guy;

👎 Examples of incorrect code

var foo = RegExp("a*b*c", "l"); // L don1t exists

No Obscure Range


The character range operator (the - inside character classes) can easily be misused (mostly unintentionally) to construct non-obvious character class. This rule will disallow all non-obvious uses of the character range operator.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-obscure-range.html

👍 Examples of correct code

var foo = /[a-z]/;
var foo = /[J-O]/;
var foo = /[1-9]/;
var foo = /[\x00-\x40]/;
var foo = /[\0-\uFFFF]/;
var foo = /[\0-\u{10FFFF}]/u;
var foo = /[\1-\5]/;
var foo = /[\cA-\cZ]/;

👎 Examples of incorrect code

var foo = /[A-\x43]/;
var foo = /[\41-\x45]/;
var foo = /[!-$]/;
var foo = /[😀-😄]/u;

No Trivially Nested Quantifier


The character range operator (the - inside character classes) can easily be misused (mostly unintentionally) to construct non-obvious character class. This rule will disallow all non-obvious uses of the character range operator.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-obscure-range.html

👍 Examples of correct code

var foo = /[a-z]/;
var foo = /[J-O]/;
var foo = /[1-9]/;
var foo = /[\x00-\x40]/;
var foo = /[\0-\uFFFF]/;
var foo = /[\0-\u{10FFFF}]/u;
var foo = /[\1-\5]/;
var foo = /[\cA-\cZ]/;

👎 Examples of incorrect code

var foo = /[A-\x43]/;
var foo = /[\41-\x45]/;
var foo = /[!-$]/;
var foo = /[😀-😄]/u;

No Unused Capturing Group


This rule reports unused capturing groups.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-unused-capturing-group.html

👍 Examples of correct code

var matches = '2000-12-31 2001-01-01'.match(/(\d{4})-(\d{2})-(\d{2})/)
var y = matches[1] // "2000"
var m = matches[2] // "12"
var d = matches[3] // "31"

👎 Examples of incorrect code

var isDate = /(\d{4})-(\d{2})-(\d{2})/.test('2000-12-31') // true But group never used

No Useless Character Class


This rule reports character classes that defines only one character.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-useless-character-class.html

👍 Examples of correct code

var foo = /abc/;

👎 Examples of incorrect code

var foo = /a[b]c/;

No Useless Flag


This will point out present regex flags that do not change the pattern.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-useless-character-class.html

👍 Examples of correct code

var foo = /a|b/i;

var foo = /^foo$/m;

var foo = /a.*?b/s;

const regex1 = /foo/y;
const str = 'table football, football';
regex1.lastIndex = 6
var array = regex1.exec(str)

👎 Examples of incorrect code

var foo = /\.{3}/i;
var foo = /\w+/i;

var foo = /foo|[^\r\n]*/m;
var foo = /a|b/m;

var foo = /[.:]/s;
var foo = /^foo$/s;

str.split(/foo/y);

No Useless Lazy


This rule reports lazy quantifiers that don't need to by lazy.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-useless-lazy.html

👍 Examples of correct code

var foo = /a*?/;
var foo = /a+?/;
var foo = /a{4,}?/;
var foo = /a{2,4}?/;
var foo = /a[\s\S]*?bar/;

👎 Examples of incorrect code

var foo = /a{1}?/;
var foo = /a{4}?/;
var foo = /a{2,2}?/;
var foo = /ab+?c/;

No Useless Quantifier


This rule reports quantifiers that can trivially be removed without affecting the pattern.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-useless-quantifier.html

👍 Examples of correct code

var foo = /a*/;
var foo = /(?:a|b?)??/;
var foo = /(?:\b|(?!a))*/;

👎 Examples of incorrect code

var foo = /a{1}/;
var foo = /(?:\b)+/;
var foo = /(?:a+b*|c*)?/;

No Useless Range


This rule reports unnecessary range of characters by using a hyphen. e.g. [a-a]

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-useless-range.html

👍 Examples of correct code

var foo = /[a]/
var foo = /[ab]/

👎 Examples of incorrect code

var foo = /[a-a]/
var foo = /[a-b]/

No Useless Two Num Quantifier


This rule reports unnecessary {n,m} quantifiers.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-useless-two-nums-quantifier.html

👍 Examples of correct code

var foo = /a{0,1}/;
var foo = /a{1,5}/;
var foo = /a{1,}/;
var foo = /a{2}/;

👎 Examples of incorrect code

var foo = /a{0,0}/;
var foo = /a{1,1}/;
var foo = /a{2,2}/;

No Zero Quantifier


This rule reports quantifiers with a maximum of zero. These quantifiers trivially do not affect the pattern is any way and can be removed.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-zero-quantifier.html

👍 Examples of correct code

var foo = /a?/;
var foo = /a{0,}/;
var foo = /a{0,1}/;

👎 Examples of incorrect code

var foo = /a{0}/;
var foo = /a{0,0}?/;
var foo = /(a){0}/;

Optimal LookAround Quantifier


Non-constant quantifiers are quantifiers that describe a range.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/optimal-lookaround-quantifier.html

👍 Examples of correct code

// lookaheads
var foo = /\w+(?=\s*:)/;

// lookbehinds
var foo = /(?<=ab+)/;

👎 Examples of incorrect code

// lookaheads
var foo = /(?=ab+)/; // == /(?=ab)/
var foo = /(?=ab*)/; // == /(?=a)/
var foo = /(?!ab?)/; // == /(?!a)/
var foo = /(?!ab{6,})/; // == /(?!ab{6})/

// lookbehinds
var foo = /(?<=a+b)/; // == /(?<=ab)/
var foo = /(?<!\w*\s*,)/; // == /(?<!,)/

Optimal Quantifier Concatenation


If two quantified characters, character classes, or characters are concatenated, the quantifiers can be optimized if either of the characters elements is a subset of the other.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/optimal-lookaround-quantifier.html

👍 Examples of correct code

var foo = /\w+\d{4}/;
var foo = /\w{3,5}\d*/;
var foo = /a+b+c+d+[abc]+/;
var foo = /a\w*/;

👎 Examples of incorrect code

var foo = /\w+\d+/;
var foo = /\w+\d?/;
var foo = /[ab]*(?:a|b)/;
var foo = /\w+(?:(a)|b)*/;

Prefer Quantifier


This rule is aimed to use quantifiers instead of consecutive characters in regular expressions.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/optimal-lookaround-quantifier.html

👍 Examples of correct code

var foo = /\d{4}-\d{2}-\d{2}/;

👎 Examples of incorrect code

var foo = /\d\d\d\d-\d\d-\d\d/;

Prefer Range


This rule is aimed to use ranges instead of multiple adjacent characters in character class.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/prefer-range.html

👍 Examples of correct code

var foo = /[0-9]/
var foo = /[a-f]/

👎 Examples of incorrect code

var foo = /[123456789]/
var foo = /[a-cd-f]/

Sort Alternatives


This rule will only sort alternatives if reordering the alternatives doesn't affect the pattern.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/sort-alternatives.html

👍 Examples of correct code

var foo = /\b(1|2|3)\b/;
var foo = /\b(alpha|beta|gamma)\b/;

👎 Examples of incorrect code

var foo = /\b(2|1|3)\b/;
var foo = /__(?:Foo|Bar)__/;
var foo = /\((?:TM|R|C)\)/;

Hexadecimal Escape


This rule aims is enforces the consistent use of hexadecimal escapes.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/hexadecimal-escape.html

👍 Examples of correct code

var foo = /\x0a/;

👎 Examples of incorrect code

var foo = /\u000a/;
var foo = /\u{a}/u;

Match Any


This rule enforces the regular expression notation to match any character. e.g. [\s\S], [^], /./s (dotAll) and more.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/match-any.html

👍 Examples of correct code

var foo = /[\s\S]/;
var foo = /./s;

👎 Examples of incorrect code

var foo = /[\S\s]/;
var foo = /[^]/;
var foo = /[\d\D]/;
var foo = /[\w\W]/;

No Useless Escape


This rule reports unnecessary escape characters in RegExp. You may be able to find another mistake by finding unnecessary escapes.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-useless-escape.html

👍 Examples of correct code

var foo = /\[/
var foo = /\\/

👎 Examples of incorrect code

var foo = /\a/
var foo = /\x7/
var foo = /\u41/
var foo = /\u{[41]}/

No Useless Non Capturing Group


This rule reports unnecessary non-capturing group

https://ota-meshi.github.io/eslint-plugin-regexp/rules/prefer-character-class.html

👍 Examples of correct code

var foo = /(?:abcd)?/.test(str)
var foo = /a(?:ab|cd)/.test(str)

👎 Examples of incorrect code

var foo = /(?:ab|cd)/.test(str)
var foo = /(?:abcd)/.test(str)
var foo = /(?:[a-d])/.test(str)
var foo = /(?:[a-d])|e/.test(str)
var foo = /(?:a|(?:b|c)|d)/.test(str)

Prefer Character Class


Instead of single-character alternatives (e.g. (?:a|b|c)),character classes (e.g. [abc]) should be preferred.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-useless-non-capturing-group.html

👍 Examples of correct code

var foo = /[abc]/
var foo = /(?:a|b)/

👎 Examples of incorrect code

var foo = /a|b|c/
var foo = /(a|b|c)c/
var foo = /.|\s/
var foo = /(\w|\d)+:/

Prefer D


This rule is aimed at using \d instead of [0-9] in regular expressions.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/prefer-d.html

👍 Examples of correct code

var foo = /\d/;
var foo = /\D/;

👎 Examples of incorrect code

var foo = /[0-9]/;
var foo = /[^0-9]/;

Prefer Plus


This rule is aimed at using + quantifier instead of {1,} in regular expressions.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/prefer-plus-quantifier.html

👍 Examples of correct code

var foo = /a+/;

👎 Examples of incorrect code

var foo = /a{1,}/;

Prefer Question Quantifier


This rule is aimed at using ? quantifier instead of {0,1} in regular expressions.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/prefer-question-quantifier.html

👍 Examples of correct code

var foo = /a?/;

👎 Examples of incorrect code

var foo = /a{0,1}/;

Prefer Star Quantifier


This rule is aimed at using * quantifier instead of {0,} in regular expressions.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/prefer-star-quantifier.html

👍 Examples of correct code

var foo = /a*/

👎 Examples of incorrect code

var foo = /a{0,}/;

Prefer Unicode Code Point Escapes


This rule enforces the use of Unicode codepoint escapes instead of Unicode escapes using surrogate pairs.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/prefer-unicode-codepoint-escapes.html

👍 Examples of correct code

var foo = /\u{1f600}/u
var foo = /😀/u

👎 Examples of incorrect code

var foo = /\ud83d\ude00/u

Prefer W


This rule is aimed at using \w in regular expressions.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/prefer-w.html

👍 Examples of correct code

var foo = /\w/;
var foo = /\W/;

👎 Examples of incorrect code

var foo = /[0-9a-zA-Z_]/;
var foo = /[^0-9a-zA-Z_]/;
var foo = /[0-9a-z_]/i;
var foo = /[0-9a-z_-]/i;

Sort Character Class Elements


This rule checks elements of character classes are sorted.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/sort-character-class-elements.html

👍 Examples of correct code

var foo = /[abcdef]/
var foo = /[ab-f]/

👎 Examples of incorrect code

var foo = /[bcdefa]/
var foo = /[b-fa]/

Sort Flags


The flags of JavaScript regular expressions should be sorted alphabetically because the flags of the .flags property of RegExp objects are always sorted. Not sorting flags in regex literals misleads readers into thinking that the order may have some purpose which it doesn't.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/sort-flags.html

👍 Examples of correct code

var foo = /abc/
var foo = /abc/iu
var foo = /abc/gimsuy

👎 Examples of incorrect code

var foo = /abc/mi
var foo = /abc/us

Prefer Named Capture Group


This rule reports capturing groups without a name.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/prefer-named-capture-group.html

👍 Examples of correct code

var foo = /(?<foo>ba+r)/;
var foo = /\b(?:foo)+\b/;

👎 Examples of incorrect code

var foo = /\b(foo)+\b/;

Prefer Regexp Exec


RegExp#exec is faster than String#match and both work the same when not using the /g flag.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/prefer-regexp-exec.html https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/prefer-regexp-exec.md

👍 Examples of correct code

/thing/.exec('something');

'some things are just things'.match(/thing/g);

const text = 'something';
const search = /thing/;
search.exec(text);

👎 Examples of incorrect code

'something'.match(/thing/);

'some things are just things'.match(/thing/);

const text = 'something';
const search = /thing/;
text.match(search);

Existing Groups


Replacement strings should reference existing regular expression groups

https://sonarsource.github.io/rspec/#/rspec/S6328/javascript

👍 Examples of correct code

const str = 'James Bond';
console.log(str.replace(/(\w+)\s(\w+)/, '$1, $0 $1'));
console.log(str.replace(/(?<firstName>\w+)\s(?<lastName>\w+)/, '$<surname>, $<firstName> $<surname>'));

👎 Examples of incorrect code

const str = 'James Bond';
console.log(str.replace(/(\w+)\s(\w+)/, '$2, $1 $2'));
console.log(str.replace(/(?<firstName>\w+)\s(?<lastName>\w+)/, '$<lastName>, $<firstName> $<lastName>'));

No Misleading Capturing Group


This rule reports capturing groups that capture less text than their pattern might suggest.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-misleading-capturing-group.html

👍 Examples of correct code

var foo = /a+(b*)/

👎 Examples of incorrect code

var foo = /a+(a*)/
var foo = /\w+(\d*)/
var foo = /^(a*).+/

No Extra Lookaround Assertions


The last positive lookahead assertion within a lookahead assertion is the same without lookahead assertions. Also, The first positive lookbehind assertion within a lookbehind assertion is the same without lookbehind assertions. They can be inlined or converted to group.

https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-extra-lookaround-assertions.html

👍 Examples of correct code

var ts = 'JavaScript'.replace(/Java(?=Script)/u, 'Type');
var java = 'JavaScript'.replace(/(?<=Java)Script/u, '');
var re1 = /a(?=bc)/u;
var re2 = /a(?=b(?:c|C))/u;
var re3 = /(?<=ab)c/u;
var re4 = /(?<=(?:a|A)b)c/u;

👎 Examples of incorrect code

var ts = 'JavaScript'.replace(/Java(?=Scrip(?=t))/u, 'Type');
var java = 'JavaScript'.replace(/(?<=(?<=J)ava)Script/u, '');
var re1 = /a(?=b(?=c))/u;
var re2 = /a(?=b(?=c|C))/u;
var re3 = /(?<=(?<=a)b)c/u;
var re4 = /(?<=(?<=a|A)b)c/u;

Security

Eval Disabled


JavaScript's eval() function is potentially dangerous and is often misused. Using eval() on untrusted code can open a program up to several different injection attacks. The use of eval() in most contexts can be substituted for a better, alternative approach to a problem. Disallow the use of eval()-like methods

https://eslint.org/docs/rules/no-eval#no-eval https://eslint.org/docs/rules/no-implied-eval https://sonarsource.github.io/rspec/#/rspec/S1523/javascript https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-implied-eval.md

👍 Examples of correct code

var obj = { x: "foo" },
    key = "x",
    value = obj[key];

class A {
    foo() {
        // This is a user-defined method.
        this.eval("var a = 0");
    }

    eval() {
    }

    static {
        // This is a user-defined static method.
        this.eval("var a = 0");
    }

    static eval() {
    }
}

👎 Examples of incorrect code

var obj = { x: "foo" },
    key = "x",
    value = eval("obj." + key);

(0, eval)("var a = 0");

var foo = eval;
foo("var a = 0");

// This `this` is the global object.
this.eval("var a = 0");

Detect Unsafe Regex


There are many ways to block the event loop, one way an attacker can do that is with Regular Expression Denial of Service (ReDoS).

https://github.com/nodesecurity/eslint-plugin-security/blob/main/docs/regular-expression-dos-and-node.md

👍 Examples of correct code

 var expression = /^[\w+\-.]+@[\d\-A-Za-z]+\.[\d\-.A-Za-z]+$/

👎 Examples of incorrect code

var expression = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

Buffer No Assert


Detect calls to buffer with noAssert flag set.

From the Node.js API docs: "Setting noAssert to true skips validation of the offset. This allows the offset to be beyond the end of the Buffer."

https://github.com/nodesecurity/eslint-plugin-security#detect-buffer-noassert

👍 Examples of correct code

👎 Examples of incorrect code

/** https://nodejs.org/api/buffer.html */

No Exec Child Process


Detect instances of child_process & non-literal exec()

https://github.com/nodesecurity/eslint-plugin-security/blob/main/docs/avoid-command-injection-node.md

👍 Examples of correct code

var child_process = require('child_process');

var path = '.';
child_process.execFile('/bin/ls', ['-l', path], function (err, result) {
  console.log(result);
});

// Or

var child_process = require('child_process');

var path = '.';
var ls = child_process.spawn('/bin/ls', ['-l', path]);
ls.stdout.on('data', function (data) {
  console.log(data.toString());
});

👎 Examples of incorrect code

var path = 'user input';
child_process.exec('ls -l ' + path, function (err, data) {
  console.log(data);
});

No Mustache Scape


Detects object.escapeMarkup = false, which can be used with some template engines to disable escaping of HTML entities. This can lead to Cross-Site Scripting (XSS) vulnerabilities.

More information: OWASP XSS

https://github.com/nodesecurity/eslint-plugin-security#detect-disable-mustache-escape

👍 Examples of correct code

// No remove object.escapeMarkup = false

👎 Examples of incorrect code

object.escapeMarkup = false

No Csrf Before Method Override


As the declaration order of middlewares determines the execution stack in Connect, it is possible to abuse this functionality in order to bypass the standard Connect's anti-CSRF protection.

https://github.com/nodesecurity/eslint-plugin-security/blob/main/docs/bypass-connect-csrf-protection-by-abusing.md

👍 Examples of correct code

app.use(express.csrf())
app.use(express.methodOverride())

👎 Examples of incorrect code

app.use(express.methodOverride())
app.use(express.csrf())

No Literal Fs Filename


Detects variable in filename argument of fs calls, which might allow an attacker to access anything on your system.

https://github.com/nodesecurity/eslint-plugin-security#detect-non-literal-fs-filename

👍 Examples of correct code

👎 Examples of incorrect code

No Pseudo Random Bytes


Detects if pseudoRandomBytes() is in use, which might not give you the randomness you need and expect.

https://github.com/nodesecurity/eslint-plugin-security#detect-non-literal-fs-filename https://sonarsource.github.io/rspec/#/rspec/S2245/javascript

👍 Examples of correct code

var crypto = require("crypto")

const random = crypto.randomBytes(60);

👎 Examples of incorrect code

const random = Math.random();

Prevent Secret Token


Prevent commit with token, passwords, keys etc.

👍 Examples of correct code

const apiKey = process.env.apiKey;

👎 Examples of incorrect code

const apiKey = "123456"

Prevent Literal Code


Prevent attack in your code

https://github.com/nodesecurity/eslint-plugin-security/blob/HEAD/docs/regular-expression-dos-and-node.md

👍 Examples of correct code

require('../name');
require(`../name`);

👎 Examples of incorrect code

require(name);
require('../' + name);
require(`../${name}`);
require(name());

No Import Dynamic


This rule checks every call to require() that uses expressions for the module name argument.

https://github.com/import-js/eslint-plugin-import/blob/HEAD/docs/rules/no-dynamic-require.md

👍 Examples of correct code

require('../name');
require(`../name`);

👎 Examples of incorrect code

require(name);
require('../' + name);
require(`../${name}`);
require(name());

Security SSL


Authorizing HTTP communications with S3 buckets is security-sensitive

https://sonarsource.github.io/rspec/#/rspec/S6249/javascript

👍 Examples of correct code

const s3 = require('aws-cdk-lib/aws-s3');

const bucket = new s3.Bucket(this, 'example', {
    bucketName: 'example',
    versioned: true,
    publicReadAccess: false,
    enforceSSL: true
});

👎 Examples of incorrect code

const s3 = require('aws-cdk-lib/aws-s3');

const bucket = new s3.Bucket(this, 'example'); // Sensitive

Security Encrypt Access


Allowing public ACLs or policies on a S3 bucket is security-sensitive Disabling server-side encryption of S3 buckets is security-sensitive

By default S3 buckets are private, it means that only the bucket owner can access it. This access control can be relaxed with ACLs or policies. To prevent permissive policies or ACLs to be set on a S3 bucket the following booleans settings can be enabled:

https://sonarsource.github.io/rspec/#/rspec/S6281/javascript https://sonarsource.github.io/rspec/#/rspec/S6245/javascript

👍 Examples of correct code

const s3 = require('aws-cdk-lib/aws-s3');

new s3.Bucket(this, 'id', {
    bucketName: 'bucket',
    blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL
});

new s3.Bucket(this, 'id', {
    blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
    encryption: s3.BucketEncryption.KMS_MANAGED
});

# Alternatively with a KMS key managed by the user.

new s3.Bucket(this, 'id', {
    blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
    encryption: s3.BucketEncryption.KMS_MANAGED,
    encryptionKey: access_key
});

👎 Examples of incorrect code

const s3 = require('aws-cdk-lib/aws-s3');

new s3.Bucket(this, 'id', {
    bucketName: 'bucket'
}); // Sensitive

Certificate Transparency


Disabling Certificate Transparency monitoring is security-sensitive

Implement Expect-CT HTTP header which instructs the web browser to check public CT logs in order to verify if the website appears inside and if it is not, the browser will block the request and display a warning to the user.

https://sonarsource.github.io/rspec/#/rspec/S5742/javascript

👍 Examples of correct code

const express = require('express');
const helmet = require('helmet');

let app = express();

app.use(helmet.expectCt({
  enforce: true,
  maxAge: 86400
})); // Compliant

👎 Examples of incorrect code

const express = require('express');
const helmet = require('helmet');

let app = express();

app.use(
    helmet({
      expectCt: false // Sensitive
    })
);

No Log confidential information


Log management is an important topic, especially for the security of a web application, to ensure user activity, including potential attackers, is recorded and available for an analyst to understand what’s happened on the web application in case of malicious activities.

https://sonarsource.github.io/rspec/#/rspec/S5757/javascript

👍 Examples of correct code

const { Signale } = require('signale');

const CREDIT_CARD_NUMBERS = fetchFromWebForm()
// here we suppose the credit card numbers are retrieved somewhere and CREDIT_CARD_NUMBERS looks like
// ["1234-5678-0000-9999", "1234-5678-0000-8888"]; for instance

const options = {
  secrets: ["([0-9]{4}-?)+"]
};

const logger = new Signale(options); // Compliant

CREDIT_CARD_NUMBERS.forEach(function(CREDIT_CARD_NUMBER) {
  logger.log('The customer ordered products with the credit card number = %s', CREDIT_CARD_NUMBER);
});

👎 Examples of incorrect code

const { Signale } = require('signale');

const CREDIT_CARD_NUMBERS = fetchFromWebForm()
// here we suppose the credit card numbers are retrieved somewhere and CREDIT_CARD_NUMBERS looks like
//  ["1234-5678-0000-9999", "1234-5678-0000-8888"]; for instance

const options = {
  secrets: []         // empty list of secrets
};

const logger = new Signale(options); // Sensitive

CREDIT_CARD_NUMBERS.forEach(function(CREDIT_CARD_NUMBER) {
  logger.log('The customer ordered products with the credit card number = %s', CREDIT_CARD_NUMBER);
});

Content Length


Rejecting requests with significant content length is a good practice to control the network traffic intensity and thus resource consumption in order to prevents DoS attacks.

https://sonarsource.github.io/rspec/#/rspec/S5693/javascript

👍 Examples of correct code

const form = new Formidable();
form.maxFileSize = 8000000; // Compliant: 8MB

let diskUpload = multer({
  storage: diskStorage,
  limits: {
     fileSize: 8000000 // Compliant: 8MB
  }
});

let jsonParser = bodyParser.json(); // Compliant, when the limit is not defined, the default value is set to 100kb
let urlencodedParser = bodyParser.urlencoded({ extended: false, limit: "2mb" }); // Compliant

👎 Examples of incorrect code

const form = new Formidable();
form.maxFileSize = 10000000; // Sensitive: 10MB is more than the recommended limit of 8MB

const formDefault = new Formidable(); // Sensitive, the default value is 200MB

let diskUpload = multer({
  storage: diskStorage,
  limits: {
    fileSize: 10000000; // Sensitive: 10MB is more than the recommended limit of 8MB
  }
});

let diskUploadUnlimited = multer({ // Sensitive: the default value is no limit
  storage: diskStorage,
});

// 4MB is more than the recommended limit of 2MB for non-file-upload requests
let jsonParser = bodyParser.json({ limit: "4mb" }); // Sensitive
let urlencodedParser = bodyParser.urlencoded({ extended: false, limit: "4mb" }); // Sensitive

Anti Trojan Source No Bidi


The trick is to use Unicode control characters to reorder tokens in source code at the encoding level. These visually reordered tokens can be used to display logic that, while semantically correct, diverges from the logic presented by the logical ordering of source code tokens.

https://trojansource.codes/ https://github.com/lirantal/eslint-plugin-anti-trojan-source https://github.com/eslint-community/eslint-plugin-security/blob/main/docs/rules/detect-bidi-characters.md

Cookie Httponly


When a cookie is configured with the HttpOnly attribute set to true, the browser guaranties that no client-side script will be able to read it. In most cases, when a cookie is created, the default value of HttpOnly is false and it’s up to the developer to decide whether or not the content of the cookie can be read by the client-side script. As a majority of Cross-Site Scripting (XSS) attacks target the theft of session-cookies, the HttpOnly attribute can help to reduce their impact as it won’t be possible to exploit the XSS vulnerability to steal session-cookies.

https://sonarsource.github.io/rspec/#/rspec/S3330/javascript https://sonarsource.github.io/rspec/#/rspec/S2255/javascript

let session = cookieSession({
  httpOnly: true,// Compliant
});  // Compliant

const express = require('express');
const session = require('express-session');

let app = express();
app.use(session({
  cookie:
  {
    httpOnly: true // Compliant
  }
}));

let cookies = new Cookies(req, res, { keys: keys });

cookies.set('LastVisit', new Date().toISOString(), {
  httpOnly: true // Compliant
}); // Compliant

const cookieParser = require('cookie-parser');
const csrf = require('csurf');
const express = require('express');

let csrfProtection = csrf({ cookie: { httpOnly: true }}); // Compliant

👎 Examples of incorrect code

let session = cookieSession({
  httpOnly: false,// Sensitive
});  // Sensitive

const express = require('express');
const session = require('express-session');

let app = express()
app.use(session({
  cookie:
  {
    httpOnly: false // Sensitive
  }
}));

let cookies = new Cookies(req, res, { keys: keys });

cookies.set('LastVisit', new Date().toISOString(), {
  httpOnly: false // Sensitive
}); // Sensitive

const cookieParser = require('cookie-parser');
const csrf = require('csurf');
const express = require('express');

let csrfProtection = csrf({ cookie: { httpOnly: false }}); // Sensitive

Protect XSS Render


Disabling auto-escaping in template engines is security-sensitive

https://sonarsource.github.io/rspec/#/rspec/S5247/javascript

let Mustache = require("mustache");

let rendered = Mustache.render(template, { name: inputName });

// or

const Handlebars = require('handlebars');

let source = "<p>attack {{name}}</p>";
let data = { "name": "<b>Alan</b>" };

let template = Handlebars.compile(source);

// or

let md = require('markdown-it')();

let result = md.render('# <b>attack</b>');

// or

const marked = require('marked');

marked.setOptions({
  renderer: new marked.Renderer()
}); // Compliant by default sanitize is set to true

console.log(marked("# test <b>attack/b>"));

// or

let kramed = require('kramed');

let options = {
  renderer: new kramed.Renderer({
    sanitize: true // Compliant
  })
};

console.log(kramed('Attack [xss?](javascript:alert("xss")).', options));

👎 Examples of incorrect code

let Mustache = require("mustache");

Mustache.escape = function(text) {return text;}; // Sensitive

let rendered = Mustache.render(template, { name: inputName });

// or

const Handlebars = require('handlebars');
let source = "<p>attack {{name}}</p>";
let template = Handlebars.compile(source, { noEscape: true }); // Sensitive

// or

const markdownIt = require('markdown-it');
let md = markdownIt({
  html: true // Sensitive
});

let result = md.render('# <b>attack</b>');

// or

const marked = require('marked');

marked.setOptions({
  renderer: new marked.Renderer(),
  sanitize: false // Sensitive
});

console.log(marked("# test <b>attack/b>"));

// or

let kramed = require('kramed');

var options = {
  renderer: new kramed.Renderer({
    sanitize: false // Sensitive
  })
};

Force Integrity


Disabling resource integrity features is security-sensitive

Fetching external resources, for example from a CDN, without verifying their integrity could impact the security of an application if the CDN gets compromised and resources are replaced by malicious ones. Resources integrity feature will block resources inclusion into an application if the pre-computed digest of the expected resource doesn’t match with the digest of the retrieved resource.

https://sonarsource.github.io/rspec/#/rspec/S5725/javascript

let script = document.createElement("script");
script.src = "https://cdnexample.com/script-v1.2.3.js";
script.integrity = "sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"; // Compliant
script.crossOrigin = "anonymous";
document.head.appendChild(script);

👎 Examples of incorrect code

let script = document.createElement("script");
script.src = "https://cdnexample.com/script-latest.js";
 // Sensitive no integrity
script.crossOrigin = "anonymous";
document.head.appendChild(script);

DNS prefetching


Allowing browsers to perform DNS prefetching is security-sensitive

https://sonarsource.github.io/rspec/#/rspec/S5743/javascript

const express = require('express');
const helmet = require('helmet');

let app = express();

app.use(
  helmet.dnsPrefetchControl({
    allow: false // Compliant
  })
);

👎 Examples of incorrect code

const express = require('express');
const helmet = require('helmet');

let app = express();

app.use(
  helmet.dnsPrefetchControl({
    allow: true // Sensitive: allowing DNS prefetching is security-sensitive
  })
);

No Prototype Builtins


Additionally, objects can have properties that shadow the builtins on Object.prototype, potentially causing unintended behavior or denial-of-service security vulnerabilities. For example, it would be unsafe for a webserver to parse JSON input from a client and call hasOwnProperty directly on the resulting object, because a malicious client could send a JSON value like {"hasOwnProperty": 1} and cause the server to crash.

To avoid subtle bugs like this, it’s better to always call these methods from Object.prototype. For example, foo.hasOwnProperty("bar") should be replaced with Object.prototype.hasOwnProperty.call(foo, "bar").

https://eslint.org/docs/latest/rules/No-Prototype-Builtins

var hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar");

var isPrototypeOfBar = Object.prototype.isPrototypeOf.call(foo, bar);

var barIsEnumerable = {}.propertyIsEnumerable.call(foo, "bar");

👎 Examples of incorrect code

var hasBarProperty = foo.hasOwnProperty("bar");

var isPrototypeOfBar = foo.isPrototypeOf(bar);

var barIsEnumerable = foo.propertyIsEnumerable("bar");

File Permissions


Setting loose POSIX file permissions is security-sensitive Dont use 777

https://sonarsource.github.io/rspec/#/rspec/S2612/javascript

const fs = require('fs');

fs.chmodSync("/tmp/fs", 0o770); // Compliant

// OR

const fs = require('fs');
const fsPromises = fs.promises;

fsPromises.chmod("/tmp/fsPromises", 0o770); // Compliant

👎 Examples of incorrect code

const fs = require('fs');

fs.chmodSync("/tmp/fs", 0o777); // Sensitive

// OR

const fs = require('fs');
const fsPromises = fs.promises;

fsPromises.chmod("/tmp/fsPromises", 0o777); // Sensitive

File Upload


These minimum restrictions should be applied when handling file uploads:

  • the file upload folder to restrict untrusted files to a specific folder.
  • the file extension of the uploaded file to prevent remote code execution.

https://sonarsource.github.io/rspec/#/rspec/S2598/javascript

const Formidable = require('formidable');

const form = new Formidable(); // Compliant
form.uploadDir = "./uploads/";
form.keepExtensions = false;

👎 Examples of incorrect code

const Formidable = require('formidable');

const form = new Formidable(); // Noncompliant, this form is not safe
form.uploadDir = ""; // because upload dir is not defined (by default os temp dir: /var/tmp or /tmp)
form.keepExtensions = true; // and file extensions are kept

Frame Ancestors


Disabling content security policy frame-ancestors directive is security-sensitive

Clickjacking attacks occur when an attacker try to trick an user to click on certain buttons/links of a legit website. This attack can take place with malicious HTML frames well hidden in an attacker website.

https://sonarsource.github.io/rspec/#/rspec/S5732/javascript

const express = require('express');
const helmet = require('helmet');

let app = express();

app.use(
  helmet.contentSecurityPolicy({
    directives: {
      // other directives
      frameAncestors: ["'example.com'"] // Compliant
    }
  })
);

👎 Examples of incorrect code

const express = require('express');
const helmet = require('helmet');

let app = express();

app.use(
  helmet.contentSecurityPolicy({
    directives: {
      // other directives
      frameAncestors: ["'none'"] // Sensitive: frameAncestors  is set to none
    }
  })
);

Hashing Insecurity


Using weak hashing algorithms is security-sensitive

https://sonarsource.github.io/rspec/#/rspec/S4790/javascript

const crypto = require("crypto");

const hash = crypto.createHash('sha512'); // Compliant

👎 Examples of incorrect code

const crypto = require("crypto");

const hash = crypto.createHash('sha1'); // Sensitive

Hidden Files


Hidden files are created automatically by many tools to save user-preferences, well-known examples are .profile, .bashrc, .bash_history or .git. To simplify the view these files are not displayed by default using operating system commands like ls.

https://sonarsource.github.io/rspec/#/rspec/S5691/javascript

👍 Examples of correct code

let serveStatic = require("serve-static");
let app = express();
// Compliant: ignore or deny are recommended values
let serveStaticMiddleware = serveStatic('public', { 'index': false, 'dotfiles': 'ignore'});

// Compliant: by default, "dotfiles" (file or directory that begins with a dot) are not served
// (with the exception that files within a directory that begins with a dot are not ignored),
// see serve-static module documentation
let serveStaticDefault = serveStatic('public', { 'index': false});
app.use(serveStaticMiddleware);

👎 Examples of incorrect code

let serveStatic = require("serve-static");
let app = express();
let serveStaticMiddleware = serveStatic('public', { 'index': false, 'dotfiles': 'allow'});   // Sensitive
app.use(serveStaticMiddleware);

No Dynamic Delete


Deleting dynamically computed keys can be dangerous and in some cases not well optimized. Using the delete operator on keys that aren't runtime constants could be a sign that you're using the wrong data structures. Using Objects with added and removed keys can cause occasional edge case bugs, such as if a key is named "hasOwnProperty".

https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-dynamic-delete.md

👍 Examples of correct code

const container: { [i: string]: number } = {
  /* ... */
};

// Constant runtime lookups by string index
delete container.aaa;

// Constants that must be accessed by []
delete container[7];
delete container['-Infinity'];

const name = 'aaa';
switch (name) {
    case "aaa":
        delete container.aaa
        break;
    case "bbb":
        delete container.bbb
        break;
    default:
        throw new Error("Not Authorized");
        break;
}

👎 Examples of incorrect code

// Can be replaced with the constant equivalents, such as container.aaa
delete container['aaa'];
delete container['Infinity'];

// Dynamic, difficult-to-reason-about lookups
const name = 'name';
delete container[name];
delete container[name.toUpperCase()];

Cors


Having a permissive Cross-Origin Resource Sharing policy is security-sensitive

https://sonarsource.github.io/rspec/#/rspec/S5122/javascript

👍 Examples of correct code

const http = require('http');
const srv = http.createServer((req, res) => {
  res.writeHead(200, { 'Access-Control-Allow-Origin': 'trustedwebsite.com' }); // Compliant
  res.end('ok');
});
srv.listen(3000);

const cors = require('cors');

let corsOptions = {
  origin: 'trustedwebsite.com' // Compliant
};

let app = express();
app.use(cors(corsOptions));

function (req, res) {
  const origin = req.header('Origin');

  if (trustedOrigins.indexOf(origin) >= 0) {
    res.setHeader('Access-Control-Allow-Origin', origin);
  }
};

👎 Examples of incorrect code

function (req, res) {
  const origin = req.header('Origin');
  res.setHeader('Access-Control-Allow-Origin', origin); // Sensitive
};

const cors = require('cors');

let app1 = express();
app1.use(cors()); // Sensitive: by default origin is set to *

let corsOptions = {
  origin: '*' // Sensitive
};

let app2 = express();
app2.use(cors(corsOptions));

const http = require('http');
const srv = http.createServer((req, res) => {
  res.writeHead(200, { 'Access-Control-Allow-Origin': '*' }); // Sensitive
  res.end('ok');
});
srv.listen(3000);

Csrf


Force CSRF protections is security-sensitive

https://sonarsource.github.io/rspec/#/rspec/S4502/javascript

👍 Examples of correct code

let csrf = require('csurf');
let express = require('express');

let csrfProtection = csrf({ cookie:  true });

let app = express();

app.post('/money_transfer', parseForm, csrfProtection, function (req, res) { // Compliant
  res.send('Money transferred')
});

let csrf = require('csurf');
let express = require('express');

app.use(csrf({ cookie: true, ignoreMethods: ["GET"] })); // Compliant

👎 Examples of incorrect code

let csrf = require('csurf');
let express = require('express');

let csrfProtection = csrf({ cookie: true });

let app = express();

// Sensitive: this operation doesn't look like protected by CSURF middleware (csrfProtection is not used)
app.post('/money_transfer', parseForm, function (req, res) {
  res.send('Money transferred');
});

// or

let csrf = require('csurf');
let express = require('express');

app.use(csrf({ cookie: true, ignoreMethods: ["POST", "GET"] })); // Sensitive as POST is unsafe method

Aws Security


Aws General Security

https://sonarsource.github.io/rspec/#/rspec/S6333/javascript https://sonarsource.github.io/rspec/#/rspec/S6329/javascript https://sonarsource.github.io/rspec/#/rspec/S6275/javascript https://sonarsource.github.io/rspec/#/rspec/S6332/javascript https://sonarsource.github.io/rspec/#/rspec/S6302/javascript https://sonarsource.github.io/rspec/#/rspec/S6304/javascript https://sonarsource.github.io/rspec/#/rspec/S6317/javascript https://sonarsource.github.io/rspec/#/rspec/S6270/javascript https://sonarsource.github.io/rspec/#/rspec/S6308/javascript https://sonarsource.github.io/rspec/#/rspec/S6303/javascript https://sonarsource.github.io/rspec/#/rspec/S6321/javascript https://sonarsource.github.io/rspec/#/rspec/S6265/javascript https://sonarsource.github.io/rspec/#/rspec/S6249/javascript https://sonarsource.github.io/rspec/#/rspec/S6281/javascript https://sonarsource.github.io/rspec/#/rspec/S6245/javascript https://sonarsource.github.io/rspec/#/rspec/S6252/javascript https://sonarsource.github.io/rspec/#/rspec/S6319/javascript https://sonarsource.github.io/rspec/#/rspec/S6327/javascript https://sonarsource.github.io/rspec/#/rspec/S6308/javascript

👍 Examples of correct code

import {aws_apigateway as apigateway} from "aws-cdk-lib"

const resource = api.root.addResource("example",{
    defaultMethodOptions:{
        authorizationType: apigateway.AuthorizationType.IAM
    }
})
resource.addMethod(
    "POST",
    new apigateway.HttpIntegration("https://example.org"),
    {
        authorizationType: apigateway.AuthorizationType.IAM
    }
)
resource.addMethod(  // authorizationType is inherited from the Resource's configured defaultMethodOptions
    "GET"
)

// or

import {aws_apigatewayv2 as apigateway} from "aws-cdk-lib"

new apigateway.CfnRoute(this, "auth", {
    apiId: api.ref,
    routeKey: "POST /auth",
    authorizationType: "AWS_IAM",
    target: exampleIntegration
})

// or

import { aws_opensearchservice as opensearchservice } from 'aws-cdk-lib';

const exampleDomain = new opensearchservice.Domain(this, 'ExampleDomain', {
  version: EngineVersion.OPENSEARCH_1_3,
  encryptionAtRest: {
    enabled: true,
  },
});

// or

import { Topic } from 'aws-cdk-lib/aws-sns';

const encryptionKey = new Key(this, 'exampleKey', {
    enableKeyRotation: true,
});

new Topic(this, 'exampleTopic', {
    masterKey: encryptionKey
});

// or

import { CfnNotebookInstance } from 'aws-cdk-lib/aws-sagemaker';

const encryptionKey = new Key(this, 'example', {
    enableKeyRotation: true,
});
new CfnNotebookInstance(this, 'example', {
    instanceType: 'instanceType',
    roleArn: 'roleArn',
    kmsKeyId: encryptionKey.keyId
});

// or

const s3 = require('aws-cdk-lib/aws-s3');

new s3.Bucket(this, 'id', {
    bucketName: 'bucket',
    versioned: true
});

// or

new s3.Bucket(this, 'id', {
    encryption: s3.BucketEncryption.KMS_MANAGED,
    encryptionKey: access_key
});

// or

const s3 = require('aws-cdk-lib/aws-s3');

const bucket = new s3.Bucket(this, 'example', {
    bucketName: 'example',
    versioned: true,
    publicReadAccess: false,
    enforceSSL: true
});

👎 Examples of incorrect code

import {aws_apigateway as apigateway} from "aws-cdk-lib"

const resource = api.root.addResource("example")
resource.addMethod(
    "GET",
    new apigateway.HttpIntegration("https://example.org"),
    {
        authorizationType: apigateway.AuthorizationType.NONE // Sensitive
    }
)

// or

import {aws_apigatewayv2 as apigateway} from "aws-cdk-lib"

new apigateway.CfnRoute(this, "no-auth", {
    apiId: api.ref,
    routeKey: "GET /no-auth",
    authorizationType: "NONE", // Sensitive
    target: exampleIntegration
})

// or

import { aws_opensearchservice as opensearchservice } from 'aws-cdk-lib';

const exampleCfnDomain = new opensearchservice.CfnDomain(this, 'ExampleCfnDomain', {
  engineVersion: 'OpenSearch_1.3',
}); // Sensitive, encryption must be explicitly enabled

// or

import { Topic, CfnTopic } from 'aws-cdk-lib/aws-sns';

new

Readme

Keywords

none

Package Sidebar

Install

npm i @odg/eslint-config

Weekly Downloads

29

Version

1.20.1

License

MIT

Unpacked Size

489 kB

Total Files

21

Last publish

Collaborators

  • dragonsgamers