npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@odg/eslint-config

v1.20.1

Published

Linter for JavaScript And Typescript project

Downloads

279

Readme

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';
cons