Showing 1,297 of 1,297 total issues
Missing trailing comma. Open
value: function sendNotice(fromId, toId, content) {}
- Read upRead up
- Exclude checks
require or disallow trailing commas (comma-dangle)
Trailing commas in object literals are valid according to the ECMAScript 5 (and ECMAScript 3!) spec. However, IE8 (when not in IE8 document mode) and below will throw an error when it encounters trailing commas in JavaScript.
var foo = {
bar: "baz",
qux: "quux",
};
Trailing commas simplify adding and removing items to objects and arrays, since only the lines you are modifying must be touched. Another argument in favor of trailing commas is that it improves the clarity of diffs when an item is added or removed from an object or array:
Less clear:
var foo = {
- bar: "baz",
- qux: "quux"
+ bar: "baz"
};
More clear:
var foo = {
bar: "baz",
- qux: "quux",
};
Rule Details
This rule enforces consistent use of trailing commas in object and array literals.
Options
This rule has a string option or an object option:
{
"comma-dangle": ["error", "never"],
// or
"comma-dangle": ["error", {
"arrays": "never",
"objects": "never",
"imports": "never",
"exports": "never",
"functions": "ignore",
}]
}
-
"never"
(default) disallows trailing commas -
"always"
requires trailing commas -
"always-multiline"
requires trailing commas when the last element or property is in a different line than the closing]
or}
and disallows trailing commas when the last element or property is on the same line as the closing]
or}
-
"only-multiline"
allows (but does not require) trailing commas when the last element or property is in a different line than the closing]
or}
and disallows trailing commas when the last element or property is on the same line as the closing]
or}
Trailing commas in function declarations and function calls are valid syntax since ECMAScript 2017; however, the string option does not check these situations for backwards compatibility.
You can also use an object option to configure this rule for each type of syntax.
Each of the following options can be set to "never"
, "always"
, "always-multiline"
, "only-multiline"
, or "ignore"
.
The default for each option is "never"
unless otherwise specified.
-
arrays
is for array literals and array patterns of destructuring. (e.g.let [a,] = [1,];
) -
objects
is for object literals and object patterns of destructuring. (e.g.let {a,} = {a: 1};
) -
imports
is for import declarations of ES Modules. (e.g.import {a,} from "foo";
) -
exports
is for export declarations of ES Modules. (e.g.export {a,};
) -
functions
is for function declarations and function calls. (e.g.(function(a,){ })(b,);
)
functions
is set to"ignore"
by default for consistency with the string option.
never
Examples of incorrect code for this rule with the default "never"
option:
/*eslint comma-dangle: ["error", "never"]*/
var foo = {
bar: "baz",
qux: "quux",
};
var arr = [1,2,];
foo({
bar: "baz",
qux: "quux",
});
Examples of correct code for this rule with the default "never"
option:
/*eslint comma-dangle: ["error", "never"]*/
var foo = {
bar: "baz",
qux: "quux"
};
var arr = [1,2];
foo({
bar: "baz",
qux: "quux"
});
always
Examples of incorrect code for this rule with the "always"
option:
/*eslint comma-dangle: ["error", "always"]*/
var foo = {
bar: "baz",
qux: "quux"
};
var arr = [1,2];
foo({
bar: "baz",
qux: "quux"
});
Examples of correct code for this rule with the "always"
option:
/*eslint comma-dangle: ["error", "always"]*/
var foo = {
bar: "baz",
qux: "quux",
};
var arr = [1,2,];
foo({
bar: "baz",
qux: "quux",
});
always-multiline
Examples of incorrect code for this rule with the "always-multiline"
option:
/*eslint comma-dangle: ["error", "always-multiline"]*/
var foo = {
bar: "baz",
qux: "quux"
};
var foo = { bar: "baz", qux: "quux", };
var arr = [1,2,];
var arr = [1,
2,];
var arr = [
1,
2
];
foo({
bar: "baz",
qux: "quux"
});
Examples of correct code for this rule with the "always-multiline"
option:
/*eslint comma-dangle: ["error", "always-multiline"]*/
var foo = {
bar: "baz",
qux: "quux",
};
var foo = {bar: "baz", qux: "quux"};
var arr = [1,2];
var arr = [1,
2];
var arr = [
1,
2,
];
foo({
bar: "baz",
qux: "quux",
});
only-multiline
Examples of incorrect code for this rule with the "only-multiline"
option:
/*eslint comma-dangle: ["error", "only-multiline"]*/
var foo = { bar: "baz", qux: "quux", };
var arr = [1,2,];
var arr = [1,
2,];
Examples of correct code for this rule with the "only-multiline"
option:
/*eslint comma-dangle: ["error", "only-multiline"]*/
var foo = {
bar: "baz",
qux: "quux",
};
var foo = {
bar: "baz",
qux: "quux"
};
var foo = {bar: "baz", qux: "quux"};
var arr = [1,2];
var arr = [1,
2];
var arr = [
1,
2,
];
var arr = [
1,
2
];
foo({
bar: "baz",
qux: "quux",
});
foo({
bar: "baz",
qux: "quux"
});
functions
Examples of incorrect code for this rule with the {"functions": "never"}
option:
/*eslint comma-dangle: ["error", {"functions": "never"}]*/
function foo(a, b,) {
}
foo(a, b,);
new foo(a, b,);
Examples of correct code for this rule with the {"functions": "never"}
option:
/*eslint comma-dangle: ["error", {"functions": "never"}]*/
function foo(a, b) {
}
foo(a, b);
new foo(a, b);
Examples of incorrect code for this rule with the {"functions": "always"}
option:
/*eslint comma-dangle: ["error", {"functions": "always"}]*/
function foo(a, b) {
}
foo(a, b);
new foo(a, b);
Examples of correct code for this rule with the {"functions": "always"}
option:
/*eslint comma-dangle: ["error", {"functions": "always"}]*/
function foo(a, b,) {
}
foo(a, b,);
new foo(a, b,);
When Not To Use It
You can turn this rule off if you are not concerned with dangling commas. Source: http://eslint.org/docs/rules/
'_x8' is defined but never used. Open
function changeNamed(_x7, _x8) {
- Read upRead up
- Exclude checks
Disallow Unused Variables (no-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.
Rule Details
This rule is aimed at eliminating unused variables, functions, and parameters of functions.
A variable is considered to be used if any of the following are true:
- It represents a function that is called (
doSomething()
) - It is read (
var y = x
) - It is passed into a function as an argument (
doSomething(x)
) - It is read inside of a function that is passed to another function (
doSomething(function() { foo(); })
)
A variable is not considered to be used if it is only ever assigned to (var x = 5
) or declared.
Examples of incorrect code for this rule:
/*eslint no-unused-vars: "error"*/
/*global some_unused_var*/
// 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;
}
Examples of correct code for this rule:
/*eslint no-unused-vars: "error"*/
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 descructured array is used.
function getY([, y]) {
return y;
}
exported
In environments outside of CommonJS or ECMAScript modules, you may use var
to create a global variable that may be used by other scripts. You can use the /* exported variableName */
comment block to indicate that this variable is being exported and therefore should not be considered unused.
Note that /* exported */
has no effect for any of the following:
- when the environment is
node
orcommonjs
- when
parserOptions.sourceType
ismodule
- when
ecmaFeatures.globalReturn
istrue
The line comment // exported variableName
will not work as exported
is not line-specific.
Examples of correct code for /* exported variableName */
operation:
/* exported global_var */
var global_var = 42;
Options
This rule takes one argument which can be a string or an object. The string settings are the same as those of the vars
property (explained below).
By default this rule is enabled with all
option for variables and after-used
for arguments.
{
"rules": {
"no-unused-vars": ["error", { "vars": "all", "args": "after-used", "ignoreRestSiblings": false }]
}
}
vars
The vars
option has two settings:
-
all
checks all variables for usage, including those in the global scope. This is the default setting. -
local
checks only that locally-declared variables are used but will allow global variables to be unused.
vars: local
Examples of correct code for the { "vars": "local" }
option:
/*eslint no-unused-vars: ["error", { "vars": "local" }]*/
/*global some_unused_var */
some_unused_var = 42;
varsIgnorePattern
The varsIgnorePattern
option specifies exceptions not to check for usage: variables whose names match a regexp pattern. For example, variables whose names contain ignored
or Ignored
.
Examples of correct code for the { "varsIgnorePattern": "[iI]gnored" }
option:
/*eslint no-unused-vars: ["error", { "varsIgnorePattern": "[iI]gnored" }]*/
var firstVarIgnored = 1;
var secondVar = 2;
console.log(secondVar);
args
The args
option has three settings:
-
after-used
- only the last argument must be used. This allows you, for instance, to have two named parameters to a function and as long as you use the second argument, ESLint will not warn you about the first. This is the default setting. -
all
- all named arguments must be used. -
none
- do not check arguments.
args: after-used
Examples of incorrect code for the default { "args": "after-used" }
option:
/*eslint no-unused-vars: ["error", { "args": "after-used" }]*/
// 1 error
// "baz" is defined but never used
(function(foo, bar, baz) {
return bar;
})();
Examples of correct code for the default { "args": "after-used" }
option:
/*eslint no-unused-vars: ["error", {"args": "after-used"}]*/
(function(foo, bar, baz) {
return baz;
})();
args: all
Examples of incorrect code for the { "args": "all" }
option:
/*eslint no-unused-vars: ["error", { "args": "all" }]*/
// 2 errors
// "foo" is defined but never used
// "baz" is defined but never used
(function(foo, bar, baz) {
return bar;
})();
args: none
Examples of correct code for the { "args": "none" }
option:
/*eslint no-unused-vars: ["error", { "args": "none" }]*/
(function(foo, bar, baz) {
return bar;
})();
ignoreRestSiblings
The ignoreRestSiblings
option is a boolean (default: false
). Using a Rest Property it is possible to "omit" properties from an object, but by default the sibling properties are marked as "unused". With this option enabled the rest property's siblings are ignored.
Examples of correct code for the { "ignoreRestSiblings": true }
option:
/*eslint no-unused-vars: ["error", { "ignoreRestSiblings": true }]*/
// 'type' is ignored because it has a rest property sibling.
var { type, ...coords } = data;
argsIgnorePattern
The argsIgnorePattern
option specifies exceptions not to check for usage: arguments whose names match a regexp pattern. For example, variables whose names begin with an underscore.
Examples of correct code for the { "argsIgnorePattern": "^_" }
option:
/*eslint no-unused-vars: ["error", { "argsIgnorePattern": "^_" }]*/
function foo(x, _y) {
return x + 1;
}
foo();
caughtErrors
The caughtErrors
option is used for catch
block arguments validation.
It has two settings:
-
none
- do not check error objects. This is the default setting. -
all
- all named arguments must be used.
caughtErrors: none
Not specifying this rule is equivalent of assigning it to none
.
Examples of correct code for the { "caughtErrors": "none" }
option:
/*eslint no-unused-vars: ["error", { "caughtErrors": "none" }]*/
try {
//...
} catch (err) {
console.error("errors");
}
caughtErrors: all
Examples of incorrect code for the { "caughtErrors": "all" }
option:
/*eslint no-unused-vars: ["error", { "caughtErrors": "all" }]*/
// 1 error
// "err" is defined but never used
try {
//...
} catch (err) {
console.error("errors");
}
caughtErrorsIgnorePattern
The caughtErrorsIgnorePattern
option specifies exceptions not to check for usage: catch arguments whose names match a regexp pattern. For example, variables whose names begin with a string 'ignore'.
Examples of correct code for the { "caughtErrorsIgnorePattern": "^ignore" }
option:
/*eslint no-unused-vars: ["error", { "caughtErrorsIgnorePattern": "^ignore" }]*/
try {
//...
} catch (ignoreErr) {
console.error("errors");
}
When Not To Use It
If you don't want to be notified about unused variables or function arguments, you can safely turn this rule off. Source: http://eslint.org/docs/rules/
Expected a default case. Open
switch (_context7.prev = _context7.next) {
- Read upRead up
- Exclude checks
Require Default Case in Switch Statements (default-case)
Some code conventions require that all switch
statements have a default
case, even if the default case is empty, such as:
switch (foo) {
case 1:
doSomething();
break;
case 2:
doSomething();
break;
default:
// do nothing
}
The thinking is that it's better to always explicitly state what the default behavior should be so that it's clear whether or not the developer forgot to include the default behavior by mistake.
Other code conventions allow you to skip the default
case so long as there is a comment indicating the omission is intentional, such as:
switch (foo) {
case 1:
doSomething();
break;
case 2:
doSomething();
break;
// no default
}
Once again, the intent here is to show that the developer intended for there to be no default behavior.
Rule Details
This rule aims to require default
case in switch
statements. You may optionally include a // no default
after the last case
if there is no default
case. The comment may be in any desired case, such as // No Default
.
Examples of incorrect code for this rule:
/*eslint default-case: "error"*/
switch (a) {
case 1:
/* code */
break;
}
Examples of correct code for this rule:
/*eslint default-case: "error"*/
switch (a) {
case 1:
/* code */
break;
default:
/* code */
break;
}
switch (a) {
case 1:
/* code */
break;
// no default
}
switch (a) {
case 1:
/* code */
break;
// No Default
}
Options
This rule accepts a single options argument:
- Set the
commentPattern
option to a regular expression string to change the default/^no default$/i
comment test pattern
commentPattern
Examples of correct code for the { "commentPattern": "^skip\\sdefault" }
option:
/*eslint default-case: ["error", { "commentPattern": "^skip\\sdefault" }]*/
switch(a) {
case 1:
/* code */
break;
// skip default
}
switch(a) {
case 1:
/* code */
break;
// skip default case
}
When Not To Use It
If you don't want to enforce a default
case for switch
statements, you can safely disable this rule.
Related Rules
- [no-fallthrough](no-fallthrough.md) Source: http://eslint.org/docs/rules/
Unexpected constant condition. Open
while (1) {
- Read upRead up
- Exclude checks
disallow constant expressions in conditions (no-constant-condition)
A constant expression (for example, a literal) as a test condition might be a typo or development trigger for a specific behavior. For example, the following code looks as if it is not ready for production.
if (false) {
doSomethingUnfinished();
}
Rule Details
This rule disallows constant expressions in the test condition of:
-
if
,for
,while
, ordo...while
statement -
?:
ternary expression
Examples of incorrect code for this rule:
/*eslint no-constant-condition: "error"*/
if (false) {
doSomethingUnfinished();
}
if (void x) {
doSomethingUnfinished();
}
for (;-2;) {
doSomethingForever();
}
while (typeof x) {
doSomethingForever();
}
do {
doSomethingForever();
} while (x = -1);
var result = 0 ? a : b;
Examples of correct code for this rule:
/*eslint no-constant-condition: "error"*/
if (x === 0) {
doSomething();
}
for (;;) {
doSomethingForever();
}
while (typeof x === "undefined") {
doSomething();
}
do {
doSomething();
} while (x);
var result = x !== 0 ? a : b;
Options
checkLoops
Set to true
by default. Setting this option to false
allows constant expressions in loops.
Examples of correct code for when checkLoops
is false
:
/*eslint no-constant-condition: ["error", { "checkLoops": false }]*/
while (true) {
doSomething();
if (condition()) {
break;
}
};
for (;true;) {
doSomething();
if (condition()) {
break;
}
};
do {
doSomething();
if (condition()) {
break;
}
} while (true)
Source: http://eslint.org/docs/rules/
Unexpected empty method 'sendCommunication'. Open
value: function sendCommunication(fromId, toId, content) {}
- Read upRead up
- Exclude checks
Disallow empty functions (no-empty-function)
Empty functions can reduce readability because readers need to guess whether it's intentional or not. So writing a clear comment for empty functions is a good practice.
function foo() {
// do nothing.
}
Especially, the empty block of arrow functions might be confusing developers. It's very similar to an empty object literal.
list.map(() => {}); // This is a block, would return undefined.
list.map(() => ({})); // This is an empty object.
Rule Details
This rule is aimed at eliminating empty functions. A function will not be considered a problem if it contains a comment.
Examples of incorrect code for this rule:
/*eslint no-empty-function: "error"*/
/*eslint-env es6*/
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) {}
}
Examples of correct code for this rule:
/*eslint no-empty-function: "error"*/
/*eslint-env es6*/
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.
}
}
Options
This rule has an option to allow specific kinds of functions to be empty.
-
allow
(string[]
) - A list of kind to allow empty functions. List items are some of the following strings. An empty array ([]
) by default.-
"functions"
- Normal functions. -
"arrowFunctions"
- Arrow functions. -
"generatorFunctions"
- Generator functions. -
"methods"
- Class methods and method shorthands of object literals. -
"generatorMethods"
- Class methods and method shorthands of object literals with generator. -
"getters"
- Getters. -
"setters"
- Setters. -
"constructors"
- Class constructors.
-
allow: functions
Examples of correct code for the { "allow": ["functions"] }
option:
/*eslint no-empty-function: ["error", { "allow": ["functions"] }]*/
function foo() {}
var foo = function() {};
var obj = {
foo: function() {}
};
allow: arrowFunctions
Examples of correct code for the { "allow": ["arrowFunctions"] }
option:
/*eslint no-empty-function: ["error", { "allow": ["arrowFunctions"] }]*/
/*eslint-env es6*/
var foo = () => {};
allow: generatorFunctions
Examples of correct code for the { "allow": ["generatorFunctions"] }
option:
/*eslint no-empty-function: ["error", { "allow": ["generatorFunctions"] }]*/
/*eslint-env es6*/
function* foo() {}
var foo = function*() {};
var obj = {
foo: function*() {}
};
allow: methods
Examples of correct code for the { "allow": ["methods"] }
option:
/*eslint no-empty-function: ["error", { "allow": ["methods"] }]*/
/*eslint-env es6*/
var obj = {
foo() {}
};
class A {
foo() {}
static foo() {}
}
allow: generatorMethods
Examples of correct code for the { "allow": ["generatorMethods"] }
option:
/*eslint no-empty-function: ["error", { "allow": ["generatorMethods"] }]*/
/*eslint-env es6*/
var obj = {
*foo() {}
};
class A {
*foo() {}
static *foo() {}
}
allow: getters
Examples of correct code for the { "allow": ["getters"] }
option:
/*eslint no-empty-function: ["error", { "allow": ["getters"] }]*/
/*eslint-env es6*/
var obj = {
get foo() {}
};
class A {
get foo() {}
static get foo() {}
}
allow: setters
Examples of correct code for the { "allow": ["setters"] }
option:
/*eslint no-empty-function: ["error", { "allow": ["setters"] }]*/
/*eslint-env es6*/
var obj = {
set foo(value) {}
};
class A {
set foo(value) {}
static set foo(value) {}
}
allow: constructors
Examples of correct code for the { "allow": ["constructors"] }
option:
/*eslint no-empty-function: ["error", { "allow": ["constructors"] }]*/
/*eslint-env es6*/
class A {
constructor() {}
}
When Not To Use It
If you don't want to be notified about empty functions, then it's safe to disable this rule.
Related Rules
- [no-empty](./no-empty.md) Source: http://eslint.org/docs/rules/
Assignment to property of function parameter '_context7'. Open
_context7.next = 2;
- Read upRead up
- Exclude checks
Disallow Reassignment of Function Parameters (no-param-reassign)
Assignment to variables declared as function parameters can be misleading and lead to confusing behavior, as modifying function parameters will also mutate the arguments
object. Often, assignment to function parameters is unintended and indicative of a mistake or programmer error.
This rule can be also configured to fail when function parameters are modified. Side effects on parameters can cause counter-intuitive execution flow and make errors difficult to track down.
Rule Details
This rule aims to prevent unintended behavior caused by modification or reassignment of function parameters.
Examples of incorrect code for this rule:
/*eslint no-param-reassign: "error"*/
function foo(bar) {
bar = 13;
}
function foo(bar) {
bar++;
}
Examples of correct code for this rule:
/*eslint no-param-reassign: "error"*/
function foo(bar) {
var baz = bar;
}
Options
This rule takes one option, an object, with a boolean property "props"
and an array "ignorePropertyModificationsFor"
. "props"
is false
by default. If "props"
is set to true
, this rule warns against the modification of parameter properties unless they're included in "ignorePropertyModificationsFor"
, which is an empty array by default.
props
Examples of correct code for the default { "props": false }
option:
/*eslint no-param-reassign: ["error", { "props": false }]*/
function foo(bar) {
bar.prop = "value";
}
function foo(bar) {
delete bar.aaa;
}
function foo(bar) {
bar.aaa++;
}
Examples of incorrect code for the { "props": true }
option:
/*eslint no-param-reassign: ["error", { "props": true }]*/
function foo(bar) {
bar.prop = "value";
}
function foo(bar) {
delete bar.aaa;
}
function foo(bar) {
bar.aaa++;
}
Examples of correct code for the { "props": true }
option with "ignorePropertyModificationsFor"
set:
/*eslint no-param-reassign: ["error", { "props": true, "ignorePropertyModificationsFor": ["bar"] }]*/
function foo(bar) {
bar.prop = "value";
}
function foo(bar) {
delete bar.aaa;
}
function foo(bar) {
bar.aaa++;
}
When Not To Use It
If you want to allow assignment to function parameters, then you can safely disable this rule.
Further Reading
Unexpected var, use let or const instead. Open
var NamedKernelManagerController = exports.NamedKernelManagerController = function () {
- Read upRead up
- Exclude checks
require let
or const
instead of var
(no-var)
ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let
and const
keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes
such as:
var count = people.length;
var enoughFood = count > sandwiches.length;
if (enoughFood) {
var count = sandwiches.length; // accidentally overriding the count variable
console.log("We have " + count + " sandwiches for everyone. Plenty for all!");
}
// our count variable is no longer accurate
console.log("We have " + count + " people and " + sandwiches.length + " sandwiches!");
Rule Details
This rule is aimed at discouraging the use of var
and encouraging the use of const
or let
instead.
Examples
Examples of incorrect code for this rule:
/*eslint no-var: "error"*/
var x = "y";
var CONFIG = {};
Examples of correct code for this rule:
/*eslint no-var: "error"*/
/*eslint-env es6*/
let x = "y";
const CONFIG = {};
When Not To Use It
In addition to non-ES6 environments, existing JavaScript projects that are beginning to introduce ES6 into their
codebase may not want to apply this rule if the cost of migrating from var
to let
is too costly.
Source: http://eslint.org/docs/rules/
'NamedKernelManagerController' is already declared in the upper scope. Open
function NamedKernelManagerController(manager) {
- Read upRead up
- Exclude checks
disallow variable declarations from shadowing variables declared in the outer scope (no-shadow)
Shadowing is the process by which a local variable shares the same name as a variable in its containing scope. For example:
var a = 3;
function b() {
var a = 10;
}
In this case, the variable a
inside of b()
is shadowing the variable a
in the global scope. This can cause confusion while reading the code and it's impossible to access the global variable.
Rule Details
This rule aims to eliminate shadowed variable declarations.
Examples of incorrect code for this rule:
/*eslint no-shadow: "error"*/
/*eslint-env es6*/
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;
}
Options
This rule takes one option, an object, with properties "builtinGlobals"
, "hoist"
and "allow"
.
{
"no-shadow": ["error", { "builtinGlobals": false, "hoist": "functions", "allow": [] }]
}
builtinGlobals
The builtinGlobals
option is false
by default.
If it is true
, the rule prevents shadowing of built-in global variables: Object
, Array
, Number
, and so on.
Examples of incorrect code for the { "builtinGlobals": true }
option:
/*eslint no-shadow: ["error", { "builtinGlobals": true }]*/
function foo() {
var Object = 0;
}
hoist
The hoist
option has three settings:
-
functions
(by default) - reports shadowing before the outer functions are defined. -
all
- reports all shadowing before the outer variables/functions are defined. -
never
- never report shadowing before the outer variables/functions are defined.
hoist: functions
Examples of incorrect code for the default { "hoist": "functions" }
option:
/*eslint no-shadow: ["error", { "hoist": "functions" }]*/
/*eslint-env es6*/
if (true) {
let b = 6;
}
function b() {}
Although let b
in the if
statement is before the function declaration in the outer scope, it is incorrect.
Examples of correct code for the default { "hoist": "functions" }
option:
/*eslint no-shadow: ["error", { "hoist": "functions" }]*/
/*eslint-env es6*/
if (true) {
let a = 3;
}
let a = 5;
Because let a
in the if
statement is before the variable declaration in the outer scope, it is correct.
hoist: all
Examples of incorrect code for the { "hoist": "all" }
option:
/*eslint no-shadow: ["error", { "hoist": "all" }]*/
/*eslint-env es6*/
if (true) {
let a = 3;
let b = 6;
}
let a = 5;
function b() {}
hoist: never
Examples of correct code for the { "hoist": "never" }
option:
/*eslint no-shadow: ["error", { "hoist": "never" }]*/
/*eslint-env es6*/
if (true) {
let a = 3;
let b = 6;
}
let a = 5;
function b() {}
Because let a
and let b
in the if
statement are before the declarations in the outer scope, they are correct.
allow
The allow
option is an array of identifier names for which shadowing is allowed. For example, "resolve"
, "reject"
, "done"
, "cb"
.
Examples of correct code for the { "allow": ["done"] }
option:
/*eslint no-shadow: ["error", { "allow": ["done"] }]*/
/*eslint-env es6*/
import async from 'async';
function foo(done) {
async.map([1, 2], function (e, done) {
done(null, e * 2)
}, done);
}
foo(function (err, result) {
console.log({ err, result });
});
Further Reading
Related Rules
- [no-shadow-restricted-names](no-shadow-restricted-names.md) Source: http://eslint.org/docs/rules/
Missing trailing comma. Open
}
- Read upRead up
- Exclude checks
require or disallow trailing commas (comma-dangle)
Trailing commas in object literals are valid according to the ECMAScript 5 (and ECMAScript 3!) spec. However, IE8 (when not in IE8 document mode) and below will throw an error when it encounters trailing commas in JavaScript.
var foo = {
bar: "baz",
qux: "quux",
};
Trailing commas simplify adding and removing items to objects and arrays, since only the lines you are modifying must be touched. Another argument in favor of trailing commas is that it improves the clarity of diffs when an item is added or removed from an object or array:
Less clear:
var foo = {
- bar: "baz",
- qux: "quux"
+ bar: "baz"
};
More clear:
var foo = {
bar: "baz",
- qux: "quux",
};
Rule Details
This rule enforces consistent use of trailing commas in object and array literals.
Options
This rule has a string option or an object option:
{
"comma-dangle": ["error", "never"],
// or
"comma-dangle": ["error", {
"arrays": "never",
"objects": "never",
"imports": "never",
"exports": "never",
"functions": "ignore",
}]
}
-
"never"
(default) disallows trailing commas -
"always"
requires trailing commas -
"always-multiline"
requires trailing commas when the last element or property is in a different line than the closing]
or}
and disallows trailing commas when the last element or property is on the same line as the closing]
or}
-
"only-multiline"
allows (but does not require) trailing commas when the last element or property is in a different line than the closing]
or}
and disallows trailing commas when the last element or property is on the same line as the closing]
or}
Trailing commas in function declarations and function calls are valid syntax since ECMAScript 2017; however, the string option does not check these situations for backwards compatibility.
You can also use an object option to configure this rule for each type of syntax.
Each of the following options can be set to "never"
, "always"
, "always-multiline"
, "only-multiline"
, or "ignore"
.
The default for each option is "never"
unless otherwise specified.
-
arrays
is for array literals and array patterns of destructuring. (e.g.let [a,] = [1,];
) -
objects
is for object literals and object patterns of destructuring. (e.g.let {a,} = {a: 1};
) -
imports
is for import declarations of ES Modules. (e.g.import {a,} from "foo";
) -
exports
is for export declarations of ES Modules. (e.g.export {a,};
) -
functions
is for function declarations and function calls. (e.g.(function(a,){ })(b,);
)
functions
is set to"ignore"
by default for consistency with the string option.
never
Examples of incorrect code for this rule with the default "never"
option:
/*eslint comma-dangle: ["error", "never"]*/
var foo = {
bar: "baz",
qux: "quux",
};
var arr = [1,2,];
foo({
bar: "baz",
qux: "quux",
});
Examples of correct code for this rule with the default "never"
option:
/*eslint comma-dangle: ["error", "never"]*/
var foo = {
bar: "baz",
qux: "quux"
};
var arr = [1,2];
foo({
bar: "baz",
qux: "quux"
});
always
Examples of incorrect code for this rule with the "always"
option:
/*eslint comma-dangle: ["error", "always"]*/
var foo = {
bar: "baz",
qux: "quux"
};
var arr = [1,2];
foo({
bar: "baz",
qux: "quux"
});
Examples of correct code for this rule with the "always"
option:
/*eslint comma-dangle: ["error", "always"]*/
var foo = {
bar: "baz",
qux: "quux",
};
var arr = [1,2,];
foo({
bar: "baz",
qux: "quux",
});
always-multiline
Examples of incorrect code for this rule with the "always-multiline"
option:
/*eslint comma-dangle: ["error", "always-multiline"]*/
var foo = {
bar: "baz",
qux: "quux"
};
var foo = { bar: "baz", qux: "quux", };
var arr = [1,2,];
var arr = [1,
2,];
var arr = [
1,
2
];
foo({
bar: "baz",
qux: "quux"
});
Examples of correct code for this rule with the "always-multiline"
option:
/*eslint comma-dangle: ["error", "always-multiline"]*/
var foo = {
bar: "baz",
qux: "quux",
};
var foo = {bar: "baz", qux: "quux"};
var arr = [1,2];
var arr = [1,
2];
var arr = [
1,
2,
];
foo({
bar: "baz",
qux: "quux",
});
only-multiline
Examples of incorrect code for this rule with the "only-multiline"
option:
/*eslint comma-dangle: ["error", "only-multiline"]*/
var foo = { bar: "baz", qux: "quux", };
var arr = [1,2,];
var arr = [1,
2,];
Examples of correct code for this rule with the "only-multiline"
option:
/*eslint comma-dangle: ["error", "only-multiline"]*/
var foo = {
bar: "baz",
qux: "quux",
};
var foo = {
bar: "baz",
qux: "quux"
};
var foo = {bar: "baz", qux: "quux"};
var arr = [1,2];
var arr = [1,
2];
var arr = [
1,
2,
];
var arr = [
1,
2
];
foo({
bar: "baz",
qux: "quux",
});
foo({
bar: "baz",
qux: "quux"
});
functions
Examples of incorrect code for this rule with the {"functions": "never"}
option:
/*eslint comma-dangle: ["error", {"functions": "never"}]*/
function foo(a, b,) {
}
foo(a, b,);
new foo(a, b,);
Examples of correct code for this rule with the {"functions": "never"}
option:
/*eslint comma-dangle: ["error", {"functions": "never"}]*/
function foo(a, b) {
}
foo(a, b);
new foo(a, b);
Examples of incorrect code for this rule with the {"functions": "always"}
option:
/*eslint comma-dangle: ["error", {"functions": "always"}]*/
function foo(a, b) {
}
foo(a, b);
new foo(a, b);
Examples of correct code for this rule with the {"functions": "always"}
option:
/*eslint comma-dangle: ["error", {"functions": "always"}]*/
function foo(a, b,) {
}
foo(a, b,);
new foo(a, b,);
When Not To Use It
You can turn this rule off if you are not concerned with dangling commas. Source: http://eslint.org/docs/rules/
All 'var' declarations must be at the top of the function scope. Open
var NamedKernelManagerControllers = exports.NamedKernelManagerControllers = {};
- Read upRead up
- Exclude checks
Require Variable Declarations to be at the top of their scope (vars-on-top)
The vars-on-top
rule generates warnings when variable declarations are not used serially at the top of a function scope or the top of a program.
By default variable declarations are always moved (“hoisted”) invisibly to the top of their containing scope by the JavaScript interpreter.
This rule forces the programmer to represent that behaviour by manually moving the variable declaration to the top of its containing scope.
Rule Details
This rule aims to keep all variable declarations in the leading series of statements. Allowing multiple declarations helps promote maintainability and is thus allowed.
Examples of incorrect code for this rule:
/*eslint vars-on-top: "error"*/
// Variable declarations in a block:
function doSomething() {
var first;
if (true) {
first = true;
}
var second;
}
// Variable declaration in for initializer:
function doSomething() {
for (var i=0; i<10; i++) {}
}
/*eslint vars-on-top: "error"*/
// Variables after other statements:
f();
var a;
Examples of correct code for this rule:
/*eslint vars-on-top: "error"*/
function doSomething() {
var first;
var second; //multiple declarations are allowed at the top
if (true) {
first = true;
}
}
function doSomething() {
var i;
for (i=0; i<10; i++) {}
}
/*eslint vars-on-top: "error"*/
var a;
f();
/*eslint vars-on-top: "error"*/
// Directives may precede variable declarations.
"use strict";
var a;
f();
// Comments can describe variables.
function doSomething() {
// this is the first var.
var first;
// this is the second var.
var second
}
Further Reading
Use the rest parameters instead of 'arguments'. Open
var routes = arguments.length <= 1 || arguments[1] === undefined ? new _routableComponent.RoutableComponentRoutes(NamedKernelManagerRoutings) : arguments[1];
- Read upRead up
- Exclude checks
Suggest using the rest parameters instead of arguments
(prefer-rest-params)
There are rest parameters in ES2015.
We can use that feature for variadic functions instead of the arguments
variable.
arguments
does not have methods of Array.prototype
, so it's a bit of an inconvenience.
Rule Details
This rule is aimed to flag usage of arguments
variables.
Examples
Examples of incorrect code for this rule:
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);
}
Examples of correct code for this rule:
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.
}
When Not To Use It
This rule should not be used in ES3/5 environments.
In ES2015 (ES6) or later, if you don't want to be notified about arguments
variables, then it's safe to disable this rule.
Related Rules
- [prefer-spread](prefer-spread.md) Source: http://eslint.org/docs/rules/
No magic number: 2. Open
var controllerClasses = arguments.length <= 2 || arguments[2] === undefined ? NamedKernelManagerControllers : arguments[2];
- Read upRead up
- Exclude checks
Disallow Magic Numbers (no-magic-numbers)
'Magic numbers' are numbers that occur multiple time in code without an explicit meaning. They should preferably be replaced by named constants.
var now = Date.now(),
inOneHour = now + (60 * 60 * 1000);
Rule Details
The no-magic-numbers
rule aims to make code more readable and refactoring easier by ensuring that special numbers
are declared as constants to make their meaning explicit.
Examples of incorrect code for this rule:
/*eslint no-magic-numbers: "error"*/
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * 0.25);
/*eslint no-magic-numbers: "error"*/
var data = ['foo', 'bar', 'baz'];
var dataLast = data[2];
/*eslint no-magic-numbers: "error"*/
var SECONDS;
SECONDS = 60;
Examples of correct code for this rule:
/*eslint no-magic-numbers: "error"*/
var TAX = 0.25;
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * TAX);
Options
ignore
An array of numbers to ignore. It's set to []
by default.
If provided, it must be an Array
.
Examples of correct code for the sample { "ignore": [1] }
option:
/*eslint no-magic-numbers: ["error", { "ignore": [1] }]*/
var data = ['foo', 'bar', 'baz'];
var dataLast = data.length && data[data.length - 1];
ignoreArrayIndexes
A boolean to specify if numbers used as array indexes are considered okay. false
by default.
Examples of correct code for the { "ignoreArrayIndexes": true }
option:
/*eslint no-magic-numbers: ["error", { "ignoreArrayIndexes": true }]*/
var data = ['foo', 'bar', 'baz'];
var dataLast = data[2];
enforceConst
A boolean to specify if we should check for the const keyword in variable declaration of numbers. false
by default.
Examples of incorrect code for the { "enforceConst": true }
option:
/*eslint no-magic-numbers: ["error", { "enforceConst": true }]*/
var TAX = 0.25;
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * TAX);
detectObjects
A boolean to specify if we should detect numbers when setting object properties for example. false
by default.
Examples of incorrect code for the { "detectObjects": true }
option:
/*eslint no-magic-numbers: ["error", { "detectObjects": true }]*/
var magic = {
tax: 0.25
};
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * magic.tax);
Examples of correct code for the { "detectObjects": true }
option:
/*eslint no-magic-numbers: ["error", { "detectObjects": true }]*/
var TAX = 0.25;
var magic = {
tax: TAX
};
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * magic.tax);
Source: http://eslint.org/docs/rules/
No magic number: 0. Open
(0, _classCallCheck3.default)(this, NamedKernelManager);
- Read upRead up
- Exclude checks
Disallow Magic Numbers (no-magic-numbers)
'Magic numbers' are numbers that occur multiple time in code without an explicit meaning. They should preferably be replaced by named constants.
var now = Date.now(),
inOneHour = now + (60 * 60 * 1000);
Rule Details
The no-magic-numbers
rule aims to make code more readable and refactoring easier by ensuring that special numbers
are declared as constants to make their meaning explicit.
Examples of incorrect code for this rule:
/*eslint no-magic-numbers: "error"*/
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * 0.25);
/*eslint no-magic-numbers: "error"*/
var data = ['foo', 'bar', 'baz'];
var dataLast = data[2];
/*eslint no-magic-numbers: "error"*/
var SECONDS;
SECONDS = 60;
Examples of correct code for this rule:
/*eslint no-magic-numbers: "error"*/
var TAX = 0.25;
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * TAX);
Options
ignore
An array of numbers to ignore. It's set to []
by default.
If provided, it must be an Array
.
Examples of correct code for the sample { "ignore": [1] }
option:
/*eslint no-magic-numbers: ["error", { "ignore": [1] }]*/
var data = ['foo', 'bar', 'baz'];
var dataLast = data.length && data[data.length - 1];
ignoreArrayIndexes
A boolean to specify if numbers used as array indexes are considered okay. false
by default.
Examples of correct code for the { "ignoreArrayIndexes": true }
option:
/*eslint no-magic-numbers: ["error", { "ignoreArrayIndexes": true }]*/
var data = ['foo', 'bar', 'baz'];
var dataLast = data[2];
enforceConst
A boolean to specify if we should check for the const keyword in variable declaration of numbers. false
by default.
Examples of incorrect code for the { "enforceConst": true }
option:
/*eslint no-magic-numbers: ["error", { "enforceConst": true }]*/
var TAX = 0.25;
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * TAX);
detectObjects
A boolean to specify if we should detect numbers when setting object properties for example. false
by default.
Examples of incorrect code for the { "detectObjects": true }
option:
/*eslint no-magic-numbers: ["error", { "detectObjects": true }]*/
var magic = {
tax: 0.25
};
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * magic.tax);
Examples of correct code for the { "detectObjects": true }
option:
/*eslint no-magic-numbers: ["error", { "detectObjects": true }]*/
var TAX = 0.25;
var magic = {
tax: TAX
};
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * magic.tax);
Source: http://eslint.org/docs/rules/
No magic number: 0. Open
var _this = (0, _possibleConstructorReturn3.default)(this, (0, _getPrototypeOf2.default)(NamedKernelManager).call(this, components, routes, controllerClasses));
- Read upRead up
- Exclude checks
Disallow Magic Numbers (no-magic-numbers)
'Magic numbers' are numbers that occur multiple time in code without an explicit meaning. They should preferably be replaced by named constants.
var now = Date.now(),
inOneHour = now + (60 * 60 * 1000);
Rule Details
The no-magic-numbers
rule aims to make code more readable and refactoring easier by ensuring that special numbers
are declared as constants to make their meaning explicit.
Examples of incorrect code for this rule:
/*eslint no-magic-numbers: "error"*/
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * 0.25);
/*eslint no-magic-numbers: "error"*/
var data = ['foo', 'bar', 'baz'];
var dataLast = data[2];
/*eslint no-magic-numbers: "error"*/
var SECONDS;
SECONDS = 60;
Examples of correct code for this rule:
/*eslint no-magic-numbers: "error"*/
var TAX = 0.25;
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * TAX);
Options
ignore
An array of numbers to ignore. It's set to []
by default.
If provided, it must be an Array
.
Examples of correct code for the sample { "ignore": [1] }
option:
/*eslint no-magic-numbers: ["error", { "ignore": [1] }]*/
var data = ['foo', 'bar', 'baz'];
var dataLast = data.length && data[data.length - 1];
ignoreArrayIndexes
A boolean to specify if numbers used as array indexes are considered okay. false
by default.
Examples of correct code for the { "ignoreArrayIndexes": true }
option:
/*eslint no-magic-numbers: ["error", { "ignoreArrayIndexes": true }]*/
var data = ['foo', 'bar', 'baz'];
var dataLast = data[2];
enforceConst
A boolean to specify if we should check for the const keyword in variable declaration of numbers. false
by default.
Examples of incorrect code for the { "enforceConst": true }
option:
/*eslint no-magic-numbers: ["error", { "enforceConst": true }]*/
var TAX = 0.25;
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * TAX);
detectObjects
A boolean to specify if we should detect numbers when setting object properties for example. false
by default.
Examples of incorrect code for the { "detectObjects": true }
option:
/*eslint no-magic-numbers: ["error", { "detectObjects": true }]*/
var magic = {
tax: 0.25
};
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * magic.tax);
Examples of correct code for the { "detectObjects": true }
option:
/*eslint no-magic-numbers: ["error", { "detectObjects": true }]*/
var TAX = 0.25;
var magic = {
tax: TAX
};
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * magic.tax);
Source: http://eslint.org/docs/rules/
Wrap an immediate function invocation in parentheses. Open
value: function () {
- Read upRead up
- Exclude checks
Require IIFEs to be Wrapped (wrap-iife)
You can immediately invoke function expressions, but not function declarations. A common technique to create an immediately-invoked function expression (IIFE) is to wrap a function declaration in parentheses. The opening parentheses causes the contained function to be parsed as an expression, rather than a declaration.
// function expression could be unwrapped
var x = function () { return { y: 1 };}();
// function declaration must be wrapped
function () { /* side effects */ }(); // SyntaxError
Rule Details
This rule requires all immediately-invoked function expressions to be wrapped in parentheses.
Options
This rule has two options, a string option and an object option.
String option:
-
"outside"
enforces always wrapping the call expression. The default is"outside"
. -
"inside"
enforces always wrapping the function expression. -
"any"
enforces always wrapping, but allows either style.
Object option:
-
"functionPrototypeMethods": true
additionally enforces wrapping function expressions invoked using.call
and.apply
. The default isfalse
.
outside
Examples of incorrect code for the default "outside"
option:
/*eslint wrap-iife: ["error", "outside"]*/
var x = function () { return { y: 1 };}(); // unwrapped
var x = (function () { return { y: 1 };})(); // wrapped function expression
Examples of correct code for the default "outside"
option:
/*eslint wrap-iife: ["error", "outside"]*/
var x = (function () { return { y: 1 };}()); // wrapped call expression
inside
Examples of incorrect code for the "inside"
option:
/*eslint wrap-iife: ["error", "inside"]*/
var x = function () { return { y: 1 };}(); // unwrapped
var x = (function () { return { y: 1 };}()); // wrapped call expression
Examples of correct code for the "inside"
option:
/*eslint wrap-iife: ["error", "inside"]*/
var x = (function () { return { y: 1 };})(); // wrapped function expression
any
Examples of incorrect code for the "any"
option:
/*eslint wrap-iife: ["error", "any"]*/
var x = function () { return { y: 1 };}(); // unwrapped
Examples of correct code for the "any"
option:
/*eslint wrap-iife: ["error", "any"]*/
var x = (function () { return { y: 1 };}()); // wrapped call expression
var x = (function () { return { y: 1 };})(); // wrapped function expression
functionPrototypeMethods
Examples of incorrect code for this rule with the "inside", { "functionPrototypeMethods": true }
options:
/* eslint wrap-iife: [2, "inside", { functionPrototypeMethods: true }] */
var x = function(){ foo(); }()
var x = (function(){ foo(); }())
var x = function(){ foo(); }.call(bar)
var x = (function(){ foo(); }.call(bar))
Examples of correct code for this rule with the "inside", { "functionPrototypeMethods": true }
options:
/* eslint wrap-iife: [2, "inside", { functionPrototypeMethods: true }] */
var x = (function(){ foo(); })()
var x = (function(){ foo(); }).call(bar)
Source: http://eslint.org/docs/rules/
No magic number: 1. Open
while (1) {
- Read upRead up
- Exclude checks
Disallow Magic Numbers (no-magic-numbers)
'Magic numbers' are numbers that occur multiple time in code without an explicit meaning. They should preferably be replaced by named constants.
var now = Date.now(),
inOneHour = now + (60 * 60 * 1000);
Rule Details
The no-magic-numbers
rule aims to make code more readable and refactoring easier by ensuring that special numbers
are declared as constants to make their meaning explicit.
Examples of incorrect code for this rule:
/*eslint no-magic-numbers: "error"*/
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * 0.25);
/*eslint no-magic-numbers: "error"*/
var data = ['foo', 'bar', 'baz'];
var dataLast = data[2];
/*eslint no-magic-numbers: "error"*/
var SECONDS;
SECONDS = 60;
Examples of correct code for this rule:
/*eslint no-magic-numbers: "error"*/
var TAX = 0.25;
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * TAX);
Options
ignore
An array of numbers to ignore. It's set to []
by default.
If provided, it must be an Array
.
Examples of correct code for the sample { "ignore": [1] }
option:
/*eslint no-magic-numbers: ["error", { "ignore": [1] }]*/
var data = ['foo', 'bar', 'baz'];
var dataLast = data.length && data[data.length - 1];
ignoreArrayIndexes
A boolean to specify if numbers used as array indexes are considered okay. false
by default.
Examples of correct code for the { "ignoreArrayIndexes": true }
option:
/*eslint no-magic-numbers: ["error", { "ignoreArrayIndexes": true }]*/
var data = ['foo', 'bar', 'baz'];
var dataLast = data[2];
enforceConst
A boolean to specify if we should check for the const keyword in variable declaration of numbers. false
by default.
Examples of incorrect code for the { "enforceConst": true }
option:
/*eslint no-magic-numbers: ["error", { "enforceConst": true }]*/
var TAX = 0.25;
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * TAX);
detectObjects
A boolean to specify if we should detect numbers when setting object properties for example. false
by default.
Examples of incorrect code for the { "detectObjects": true }
option:
/*eslint no-magic-numbers: ["error", { "detectObjects": true }]*/
var magic = {
tax: 0.25
};
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * magic.tax);
Examples of correct code for the { "detectObjects": true }
option:
/*eslint no-magic-numbers: ["error", { "detectObjects": true }]*/
var TAX = 0.25;
var magic = {
tax: TAX
};
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * magic.tax);
Source: http://eslint.org/docs/rules/
No magic number: 0. Open
case 0:
- Read upRead up
- Exclude checks
Disallow Magic Numbers (no-magic-numbers)
'Magic numbers' are numbers that occur multiple time in code without an explicit meaning. They should preferably be replaced by named constants.
var now = Date.now(),
inOneHour = now + (60 * 60 * 1000);
Rule Details
The no-magic-numbers
rule aims to make code more readable and refactoring easier by ensuring that special numbers
are declared as constants to make their meaning explicit.
Examples of incorrect code for this rule:
/*eslint no-magic-numbers: "error"*/
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * 0.25);
/*eslint no-magic-numbers: "error"*/
var data = ['foo', 'bar', 'baz'];
var dataLast = data[2];
/*eslint no-magic-numbers: "error"*/
var SECONDS;
SECONDS = 60;
Examples of correct code for this rule:
/*eslint no-magic-numbers: "error"*/
var TAX = 0.25;
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * TAX);
Options
ignore
An array of numbers to ignore. It's set to []
by default.
If provided, it must be an Array
.
Examples of correct code for the sample { "ignore": [1] }
option:
/*eslint no-magic-numbers: ["error", { "ignore": [1] }]*/
var data = ['foo', 'bar', 'baz'];
var dataLast = data.length && data[data.length - 1];
ignoreArrayIndexes
A boolean to specify if numbers used as array indexes are considered okay. false
by default.
Examples of correct code for the { "ignoreArrayIndexes": true }
option:
/*eslint no-magic-numbers: ["error", { "ignoreArrayIndexes": true }]*/
var data = ['foo', 'bar', 'baz'];
var dataLast = data[2];
enforceConst
A boolean to specify if we should check for the const keyword in variable declaration of numbers. false
by default.
Examples of incorrect code for the { "enforceConst": true }
option:
/*eslint no-magic-numbers: ["error", { "enforceConst": true }]*/
var TAX = 0.25;
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * TAX);
detectObjects
A boolean to specify if we should detect numbers when setting object properties for example. false
by default.
Examples of incorrect code for the { "detectObjects": true }
option:
/*eslint no-magic-numbers: ["error", { "detectObjects": true }]*/
var magic = {
tax: 0.25
};
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * magic.tax);
Examples of correct code for the { "detectObjects": true }
option:
/*eslint no-magic-numbers: ["error", { "detectObjects": true }]*/
var TAX = 0.25;
var magic = {
tax: TAX
};
var dutyFreePrice = 100,
finalPrice = dutyFreePrice + (dutyFreePrice * magic.tax);
Source: http://eslint.org/docs/rules/
Unexpected 'this'. Open
}, _callee, this);
- Read upRead up
- Exclude checks
Disallow this
keywords outside of classes or class-like objects. (no-invalid-this)
Under the strict mode, this
keywords outside of classes or class-like objects might be undefined
and raise a TypeError
.
Rule Details
This rule aims to flag usage of this
keywords outside of classes or class-like objects.
Basically this rule checks whether or not a function which are containing this
keywords is a constructor or a method.
This rule judges from following conditions whether or not the function is a constructor:
- The name of the function starts with uppercase.
- The function is assigned to a variable which starts with an uppercase letter.
- The function is a constructor of ES2015 Classes.
This rule judges from following conditions whether or not the function is a method:
- The function is on an object literal.
- The function is assigned to a property.
- The function is a method/getter/setter of ES2015 Classes. (excepts static methods)
And this rule allows this
keywords in functions below:
- The
call/apply/bind
method of the function is called directly. - The function is a callback of array methods (such as
.forEach()
) ifthisArg
is given. - The function has
@this
tag in its JSDoc comment.
Otherwise are considered problems.
This rule applies only in strict mode.
With "parserOptions": { "sourceType": "module" }
in the ESLint configuration, your code is in strict mode even without a "use strict"
directive.
Examples of incorrect code for this rule in strict mode:
/*eslint no-invalid-this: "error"*/
/*eslint-env es6*/
"use strict";
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);
};
foo(function() {
this.a = 0;
baz(() => this);
});
obj.foo = () => {
// `this` of arrow functions is the outer scope's.
this.a = 0;
};
var obj = {
aaa: function() {
return function foo() {
// There is in a method `aaa`, but `foo` is not a method.
this.a = 0;
baz(() => this);
};
}
};
foo.forEach(function() {
this.a = 0;
baz(() => this);
});
Examples of correct code for this rule in strict mode:
/*eslint no-invalid-this: "error"*/
/*eslint-env es6*/
"use strict";
function Foo() {
// OK, this is in a legacy style constructor.
this.a = 0;
baz(() => this);
}
class Foo {
constructor() {
// OK, this is in a constructor.
this.a = 0;
baz(() => this);
}
}
var obj = {
foo: function foo() {
// OK, this is in a method (this function is on object literal).
this.a = 0;
}
};
var obj = {
foo() {
// OK, this is in a method (this function is on object literal).
this.a = 0;
}
};
var obj = {
get foo() {
// OK, this is in a method (this function is on object literal).
return this.a;
}
};
var obj = Object.create(null, {
foo: {value: function foo() {
// OK, this is in a method (this function is on object literal).
this.a = 0;
}}
});
Object.defineProperty(obj, "foo", {
value: function foo() {
// OK, this is in a method (this function is on object literal).
this.a = 0;
}
});
Object.defineProperties(obj, {
foo: {value: function foo() {
// OK, this is in a method (this function is on object literal).
this.a = 0;
}}
});
function Foo() {
this.foo = function foo() {
// OK, this is in a method (this function assigns to a property).
this.a = 0;
baz(() => this);
};
}
obj.foo = function foo() {
// OK, this is in a method (this function assigns to a property).
this.a = 0;
};
Foo.prototype.foo = function foo() {
// OK, this is in a method (this function assigns to a property).
this.a = 0;
};
class Foo {
foo() {
// OK, this is in a method.
this.a = 0;
baz(() => this);
}
static foo() {
// OK, this is in a method (static methods also have valid this).
this.a = 0;
baz(() => this);
}
}
var foo = (function foo() {
// OK, the `bind` method of this function is called directly.
this.a = 0;
}).bind(obj);
foo.forEach(function() {
// OK, `thisArg` of `.forEach()` is given.
this.a = 0;
baz(() => this);
}, thisArg);
/** @this Foo */
function foo() {
// OK, this function has a `@this` tag in its JSDoc comment.
this.a = 0;
}
When Not To Use It
If you don't want to be notified about usage of this
keyword outside of classes or class-like objects, you can safely disable this rule.
Source: http://eslint.org/docs/rules/
Expected a default case. Open
switch (_context2.prev = _context2.next) {
- Read upRead up
- Exclude checks
Require Default Case in Switch Statements (default-case)
Some code conventions require that all switch
statements have a default
case, even if the default case is empty, such as:
switch (foo) {
case 1:
doSomething();
break;
case 2:
doSomething();
break;
default:
// do nothing
}
The thinking is that it's better to always explicitly state what the default behavior should be so that it's clear whether or not the developer forgot to include the default behavior by mistake.
Other code conventions allow you to skip the default
case so long as there is a comment indicating the omission is intentional, such as:
switch (foo) {
case 1:
doSomething();
break;
case 2:
doSomething();
break;
// no default
}
Once again, the intent here is to show that the developer intended for there to be no default behavior.
Rule Details
This rule aims to require default
case in switch
statements. You may optionally include a // no default
after the last case
if there is no default
case. The comment may be in any desired case, such as // No Default
.
Examples of incorrect code for this rule:
/*eslint default-case: "error"*/
switch (a) {
case 1:
/* code */
break;
}
Examples of correct code for this rule:
/*eslint default-case: "error"*/
switch (a) {
case 1:
/* code */
break;
default:
/* code */
break;
}
switch (a) {
case 1:
/* code */
break;
// no default
}
switch (a) {
case 1:
/* code */
break;
// No Default
}
Options
This rule accepts a single options argument:
- Set the
commentPattern
option to a regular expression string to change the default/^no default$/i
comment test pattern
commentPattern
Examples of correct code for the { "commentPattern": "^skip\\sdefault" }
option:
/*eslint default-case: ["error", { "commentPattern": "^skip\\sdefault" }]*/
switch(a) {
case 1:
/* code */
break;
// skip default
}
switch(a) {
case 1:
/* code */
break;
// skip default case
}
When Not To Use It
If you don't want to enforce a default
case for switch
statements, you can safely disable this rule.
Related Rules
- [no-fallthrough](no-fallthrough.md) Source: http://eslint.org/docs/rules/
Missing JSDoc comment. Open
function bootNamed(_x3, _x4) {
- Read upRead up
- Exclude checks
require JSDoc comments (require-jsdoc)
JSDoc is a JavaScript API documentation generator. It uses specially-formatted comments inside of code to generate API documentation automatically. For example, this is what a JSDoc comment looks like for a function:
/**
* Adds two numbers together.
* @param {int} num1 The first number.
* @param {int} num2 The second number.
* @returns {int} The sum of the two numbers.
*/
function sum(num1, num2) {
return num1 + num2;
}
Some style guides require JSDoc comments for all functions as a way of explaining function behavior.
Rule Details
This rule requires JSDoc comments for specified nodes. Supported nodes:
"FunctionDeclaration"
"ClassDeclaration"
"MethodDefinition"
"ArrowFunctionExpression"
Options
This rule has a single object option:
-
"require"
requires JSDoc comments for the specified nodes
Default option settings are:
{
"require-jsdoc": ["error", {
"require": {
"FunctionDeclaration": true,
"MethodDefinition": false,
"ClassDeclaration": false,
"ArrowFunctionExpression": false
}
}]
}
require
Examples of incorrect code for this rule with the { "require": { "FunctionDeclaration": true, "MethodDefinition": true, "ClassDeclaration": true, "ArrowFunctionExpression": true } }
option:
/*eslint "require-jsdoc": ["error", {
"require": {
"FunctionDeclaration": true,
"MethodDefinition": true,
"ClassDeclaration": true
}
}]*/
function foo() {
return 10;
}
var foo = () => {
return 10;
}
class Test{
getDate(){}
}
Examples of correct code for this rule with the { "require": { "FunctionDeclaration": true, "MethodDefinition": true, "ClassDeclaration": true, "ArrowFunctionExpression": true } }
option:
/*eslint "require-jsdoc": ["error", {
"require": {
"FunctionDeclaration": true,
"MethodDefinition": true,
"ClassDeclaration": true
}
}]*/
/**
* It returns 10
*/
function foo() {
return 10;
}
/**
* It returns test + 10
* @params {int} test - some number
* @returns {int} sum of test and 10
*/
var foo = (test) => {
return test + 10;
}
/**
* It returns 10
*/
var foo = () => {
return 10;
}
/**
* It returns 10
*/
var foo = function() {
return 10;
}
var array = [1,2,3];
array.filter(function(item) {
return item > 2;
});
/**
* It returns 10
*/
class Test{
/**
* returns the date
*/
getDate(){}
}
setTimeout(() => {}, 10); // since it's an anonymous arrow function
When Not To Use It
If you do not require JSDoc for your functions, then you can leave this rule off.
Related Rules
- [valid-jsdoc](valid-jsdoc.md) Source: http://eslint.org/docs/rules/