Showing 1,297 of 1,297 total issues
Unexpected function expression. Open
gulp.task('test-browser-watch', ['pre-test'], function(done) {
- Read upRead up
- Exclude checks
Suggest using arrow functions as callbacks. (prefer-arrow-callback)
Arrow functions are suited to callbacks, because:
-
this
keywords in arrow functions bind to the upper scope's. - The notation of the arrow function is shorter than function expression's.
Rule Details
This rule is aimed to flag usage of function expressions in an argument list.
The following patterns are considered problems:
/*eslint prefer-arrow-callback: "error"*/
foo(function(a) { return a; });
foo(function() { return this.a; }.bind(this));
The following patterns are not considered problems:
/*eslint prefer-arrow-callback: "error"*/
/*eslint-env es6*/
foo(a => a);
foo(function*() { yield; });
// this is not a callback.
var foo = function foo(a) { return a; };
// using `this` without `.bind(this)`.
foo(function() { return this.a; });
// recursively.
foo(function bar(n) { return n && n + bar(n - 1); });
Options
This rule takes one optional argument, an object which is an options object.
allowNamedFunctions
This is a boolean
option and it is false
by default. When set to true
, the rule doesn't warn on named functions used as callbacks.
Examples of correct code for the { "allowNamedFunctions": true }
option:
/*eslint prefer-arrow-callback: ["error", { "allowNamedFunctions": true }]*/
foo(function bar() {});
allowUnboundThis
This is a boolean
option and it is true
by default. When set to false
, this option allows the use of this
without restriction and checks for dynamically assigned this
values such as when using Array.prototype.map
with a context
argument. Normally, the rule will flag the use of this
whenever a function does not use bind()
to specify the value of this
constantly.
Examples of incorrect code for the { "allowUnboundThis": false }
option:
/*eslint prefer-arrow-callback: ["error", { "allowUnboundThis": false }]*/
/*eslint-env es6*/
foo(function() { this.a; });
foo(function() { (() => this); });
someArray.map(function (itm) { return this.doSomething(itm); }, someObject);
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 function expressions in an argument list, you can safely disable this rule. Source: http://eslint.org/docs/rules/
Unexpected function expression. Open
gulp.task('lint', function() {
- Read upRead up
- Exclude checks
Suggest using arrow functions as callbacks. (prefer-arrow-callback)
Arrow functions are suited to callbacks, because:
-
this
keywords in arrow functions bind to the upper scope's. - The notation of the arrow function is shorter than function expression's.
Rule Details
This rule is aimed to flag usage of function expressions in an argument list.
The following patterns are considered problems:
/*eslint prefer-arrow-callback: "error"*/
foo(function(a) { return a; });
foo(function() { return this.a; }.bind(this));
The following patterns are not considered problems:
/*eslint prefer-arrow-callback: "error"*/
/*eslint-env es6*/
foo(a => a);
foo(function*() { yield; });
// this is not a callback.
var foo = function foo(a) { return a; };
// using `this` without `.bind(this)`.
foo(function() { return this.a; });
// recursively.
foo(function bar(n) { return n && n + bar(n - 1); });
Options
This rule takes one optional argument, an object which is an options object.
allowNamedFunctions
This is a boolean
option and it is false
by default. When set to true
, the rule doesn't warn on named functions used as callbacks.
Examples of correct code for the { "allowNamedFunctions": true }
option:
/*eslint prefer-arrow-callback: ["error", { "allowNamedFunctions": true }]*/
foo(function bar() {});
allowUnboundThis
This is a boolean
option and it is true
by default. When set to false
, this option allows the use of this
without restriction and checks for dynamically assigned this
values such as when using Array.prototype.map
with a context
argument. Normally, the rule will flag the use of this
whenever a function does not use bind()
to specify the value of this
constantly.
Examples of incorrect code for the { "allowUnboundThis": false }
option:
/*eslint prefer-arrow-callback: ["error", { "allowUnboundThis": false }]*/
/*eslint-env es6*/
foo(function() { this.a; });
foo(function() { (() => this); });
someArray.map(function (itm) { return this.doSomething(itm); }, someObject);
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 function expressions in an argument list, you can safely disable this rule. Source: http://eslint.org/docs/rules/
Expected method shorthand. Open
postDetection: function(availableBrowsers) {
- Read upRead up
- Exclude checks
Require Object Literal Shorthand Syntax (object-shorthand)
EcmaScript 6 provides a concise form for defining object literal methods and properties. This syntax can make defining complex object literals much cleaner.
Here are a few common examples using the ES5 syntax:
// properties
var foo = {
x: x,
y: y,
z: z,
};
// methods
var foo = {
a: function() {},
b: function() {}
};
Now here are ES6 equivalents:
/*eslint-env es6*/
// properties
var foo = {x, y, z};
// methods
var foo = {
a() {},
b() {}
};
Rule Details
This rule enforces the use of the shorthand syntax. This applies to all methods (including generators) defined in object literals and any properties defined where the key name matches name of the assigned variable.
Each of the following properties would warn:
/*eslint object-shorthand: "error"*/
/*eslint-env es6*/
var foo = {
w: function() {},
x: function *() {},
[y]: function() {},
z: z
};
In that case the expected syntax would have been:
/*eslint object-shorthand: "error"*/
/*eslint-env es6*/
var foo = {
w() {},
*x() {},
[y]() {},
z
};
This rule does not flag arrow functions inside of object literals. The following will not warn:
/*eslint object-shorthand: "error"*/
/*eslint-env es6*/
var foo = {
x: (y) => y
};
Options
The rule takes an option which specifies when it should be applied. It can be set to one of the following values:
-
"always"
(default) expects that the shorthand will be used whenever possible. -
"methods"
ensures the method shorthand is used (also applies to generators). -
"properties"
ensures the property shorthand is used (where the key and variable name match). -
"never"
ensures that no property or method shorthand is used in any object literal. -
"consistent"
ensures that either all shorthand or all longform will be used in an object literal. -
"consistent-as-needed"
ensures that either all shorthand or all longform will be used in an object literal, but ensures all shorthand whenever possible.
You can set the option in configuration like this:
{
"object-shorthand": ["error", "always"]
}
Additionally, the rule takes an optional object configuration:
-
"avoidQuotes": true
indicates that longform syntax is preferred whenever the object key is a string literal (default:false
). Note that this option can only be enabled when the string option is set to"always"
,"methods"
, or"properties"
. -
"ignoreConstructors": true
can be used to prevent the rule from reporting errors for constructor functions. (By default, the rule treats constructors the same way as other functions.) Note that this option can only be enabled when the string option is set to"always"
or"methods"
. -
"avoidExplicitReturnArrows": true
indicates that methods are preferred over explicit-return arrow functions for function properties. (By default, the rule allows either of these.) Note that this option can only be enabled when the string option is set to"always"
or"methods"
.
avoidQuotes
{
"object-shorthand": ["error", "always", { "avoidQuotes": true }]
}
Example of incorrect code for this rule with the "always", { "avoidQuotes": true }
option:
/*eslint object-shorthand: ["error", "always", { "avoidQuotes": true }]*/
/*eslint-env es6*/
var foo = {
"bar-baz"() {}
};
Example of correct code for this rule with the "always", { "avoidQuotes": true }
option:
/*eslint object-shorthand: ["error", "always", { "avoidQuotes": true }]*/
/*eslint-env es6*/
var foo = {
"bar-baz": function() {},
"qux": qux
};
ignoreConstructors
{
"object-shorthand": ["error", "always", { "ignoreConstructors": true }]
}
Example of correct code for this rule with the "always", { "ignoreConstructors": true }
option:
/*eslint object-shorthand: ["error", "always", { "ignoreConstructors": true }]*/
/*eslint-env es6*/
var foo = {
ConstructorFunction: function() {}
};
avoidExplicitReturnArrows
{
"object-shorthand": ["error", "always", { "avoidExplicitReturnArrows": true }]
}
Example of incorrect code for this rule with the "always", { "avoidExplicitReturnArrows": true }
option:
/*eslint object-shorthand: ["error", "always", { "avoidExplicitReturnArrows": true }]*/
/*eslint-env es6*/
var foo = {
foo: (bar, baz) => {
return bar + baz;
},
qux: (foobar) => {
return foobar * 2;
}
};
Example of correct code for this rule with the "always", { "avoidExplicitReturnArrows": true }
option:
/*eslint object-shorthand: ["error", "always", { "avoidExplicitReturnArrows": true }]*/
/*eslint-env es6*/
var foo = {
foo(bar, baz) {
return bar + baz;
},
qux: foobar => foobar * 2
};
Example of incorrect code for this rule with the "consistent"
option:
/*eslint object-shorthand: [2, "consistent"]*/
/*eslint-env es6*/
var foo = {
a,
b: "foo",
};
Examples of correct code for this rule with the "consistent"
option:
/*eslint object-shorthand: [2, "consistent"]*/
/*eslint-env es6*/
var foo = {
a: a,
b: "foo"
};
var bar = {
a,
b,
};
Example of incorrect code with the "consistent-as-needed"
option, which is very similar to "consistent"
:
/*eslint object-shorthand: [2, "consistent-as-needed"]*/
/*eslint-env es6*/
var foo = {
a: a,
b: b,
};
When Not To Use It
Anyone not yet in an ES6 environment would not want to apply this rule. Others may find the terseness of the shorthand syntax harder to read and may not want to encourage it with this rule.
Further Reading
Object initializer - MDN Source: http://eslint.org/docs/rules/
Unary word operator 'typeof' must be followed by whitespace. Open
const targetObj = (typeof(target) === "function")
- Read upRead up
- Exclude checks
Require or disallow spaces before/after unary operators (space-unary-ops)
Some style guides require or disallow spaces before or after unary operators. This is mainly a stylistic issue, however, some JavaScript expressions can be written without spacing which makes it harder to read and maintain.
Rule Details
This rule enforces consistency regarding the spaces after words
unary operators and after/before nonwords
unary operators.
Examples of unary words
operators:
// new
var joe = new Person();
// delete
var obj = {
foo: 'bar'
};
delete obj.foo;
// typeof
typeof {} // object
// void
void 0 // undefined
Examples of unary nonwords
operators:
if ([1,2,3].indexOf(1) !== -1) {};
foo = --foo;
bar = bar++;
baz = !foo;
qux = !!baz;
Options
This rule has three options:
-
words
- applies to unary word operators such as:new
,delete
,typeof
,void
,yield
-
nonwords
- applies to unary operators such as:-
,+
,--
,++
,!
,!!
-
overrides
- specifies overwriting usage of spacing for each operator, word or non word. This is empty by default, but can be used to enforce or disallow spacing around operators. For example:
"space-unary-ops": [
2, {
"words": true,
"nonwords": false,
"overrides": {
"new": false,
"++": true
}
}]
In this case, spacing will be disallowed after a new
operator and required before/after a ++
operator.
Examples of incorrect code for this rule with the {"words": true, "nonwords": false}
option:
/*eslint space-unary-ops: "error"*/
typeof!foo;
void{foo:0};
new[foo][0];
delete(foo.bar);
++ foo;
foo --;
- foo;
+ "3";
/*eslint space-unary-ops: "error"*/
/*eslint-env es6*/
function *foo() {
yield(0)
}
Examples of correct code for this rule with the {"words": true, "nonwords": false}
option:
/*eslint space-unary-ops: "error"*/
// Word unary operator "delete" is followed by a whitespace.
delete foo.bar;
// Word unary operator "new" is followed by a whitespace.
new Foo;
// Word unary operator "void" is followed by a whitespace.
void 0;
// Unary operator "++" is not followed by whitespace.
++foo;
// Unary operator "--" is not preceded by whitespace.
foo--;
// Unary operator "-" is not followed by whitespace.
-foo;
// Unary operator "+" is not followed by whitespace.
+"3";
/*eslint space-unary-ops: "error"*/
/*eslint-env es6*/
function *foo() {
yield (0)
}
Source: http://eslint.org/docs/rules/
Expected indentation of 10 spaces but found 12. Open
descriptor.writable = true;
- Read upRead up
- Exclude checks
enforce consistent indentation (indent)
There are several common guidelines which require specific indentation of nested blocks and statements, like:
function hello(indentSize, type) {
if (indentSize === 4 && type !== 'tab') {
console.log('Each next indentation will increase on 4 spaces');
}
}
These are the most common scenarios recommended in different style guides:
- Two spaces, not longer and no tabs: Google, npm, Node.js, Idiomatic, Felix
- Tabs: jQuery
- Four spaces: Crockford
Rule Details
This rule enforces a consistent indentation style. The default style is 4 spaces
.
Options
This rule has a mixed option:
For example, for 2-space indentation:
{
"indent": ["error", 2]
}
Or for tabbed indentation:
{
"indent": ["error", "tab"]
}
Examples of incorrect code for this rule with the default options:
/*eslint indent: "error"*/
if (a) {
b=c;
function foo(d) {
e=f;
}
}
Examples of correct code for this rule with the default options:
/*eslint indent: "error"*/
if (a) {
b=c;
function foo(d) {
e=f;
}
}
This rule has an object option:
-
"SwitchCase"
(default: 0) enforces indentation level forcase
clauses inswitch
statements -
"VariableDeclarator"
(default: 1) enforces indentation level forvar
declarators; can also take an object to define separate rules forvar
,let
andconst
declarations. -
"outerIIFEBody"
(default: 1) enforces indentation level for file-level IIFEs. -
"MemberExpression"
(off by default) enforces indentation level for multi-line property chains (except in variable declarations and assignments) -
"FunctionDeclaration"
takes an object to define rules for function declarations.-
parameters
(off by default) enforces indentation level for parameters in a function declaration. This can either be a number indicating indentation level, or the string"first"
indicating that all parameters of the declaration must be aligned with the first parameter. -
body
(default: 1) enforces indentation level for the body of a function declaration.
-
-
"FunctionExpression"
takes an object to define rules for function expressions.-
parameters
(off by default) enforces indentation level for parameters in a function expression. This can either be a number indicating indentation level, or the string"first"
indicating that all parameters of the expression must be aligned with the first parameter. -
body
(default: 1) enforces indentation level for the body of a function expression.
-
-
"CallExpression"
takes an object to define rules for function call expressions.-
arguments
(off by default) enforces indentation level for arguments in a call expression. This can either be a number indicating indentation level, or the string"first"
indicating that all arguments of the expression must be aligned with the first argument.
-
-
"ArrayExpression"
(default: 1) enforces indentation level for elements in arrays. It can also be set to the string"first"
, indicating that all the elements in the array should be aligned with the first element. -
"ObjectExpression"
(default: 1) enforces indentation level for properties in objects. It can be set to the string"first"
, indicating that all properties in the object should be aligned with the first property.
Level of indentation denotes the multiple of the indent specified. Example:
- Indent of 4 spaces with
VariableDeclarator
set to2
will indent the multi-line variable declarations with 8 spaces. - Indent of 2 spaces with
VariableDeclarator
set to2
will indent the multi-line variable declarations with 4 spaces. - Indent of 2 spaces with
VariableDeclarator
set to{"var": 2, "let": 2, "const": 3}
will indent the multi-line variable declarations with 4 spaces forvar
andlet
, 6 spaces forconst
statements. - Indent of tab with
VariableDeclarator
set to2
will indent the multi-line variable declarations with 2 tabs. - Indent of 2 spaces with
SwitchCase
set to0
will not indentcase
clauses with respect toswitch
statements. - Indent of 2 spaces with
SwitchCase
set to1
will indentcase
clauses with 2 spaces with respect toswitch
statements. - Indent of 2 spaces with
SwitchCase
set to2
will indentcase
clauses with 4 spaces with respect toswitch
statements. - Indent of tab with
SwitchCase
set to2
will indentcase
clauses with 2 tabs with respect toswitch
statements. - Indent of 2 spaces with
MemberExpression
set to0
will indent the multi-line property chains with 0 spaces. - Indent of 2 spaces with
MemberExpression
set to1
will indent the multi-line property chains with 2 spaces. - Indent of 2 spaces with
MemberExpression
set to2
will indent the multi-line property chains with 4 spaces. - Indent of 4 spaces with
MemberExpression
set to0
will indent the multi-line property chains with 0 spaces. - Indent of 4 spaces with
MemberExpression
set to1
will indent the multi-line property chains with 4 spaces. - Indent of 4 spaces with
MemberExpression
set to2
will indent the multi-line property chains with 8 spaces.
tab
Examples of incorrect code for this rule with the "tab"
option:
/*eslint indent: ["error", "tab"]*/
if (a) {
b=c;
function foo(d) {
e=f;
}
}
Examples of correct code for this rule with the "tab"
option:
/*eslint indent: ["error", "tab"]*/
if (a) {
/*tab*/b=c;
/*tab*/function foo(d) {
/*tab*//*tab*/e=f;
/*tab*/}
}
SwitchCase
Examples of incorrect code for this rule with the 2, { "SwitchCase": 1 }
options:
/*eslint indent: ["error", 2, { "SwitchCase": 1 }]*/
switch(a){
case "a":
break;
case "b":
break;
}
Examples of correct code for this rule with the 2, { "SwitchCase": 1 }
option:
/*eslint indent: ["error", 2, { "SwitchCase": 1 }]*/
switch(a){
case "a":
break;
case "b":
break;
}
VariableDeclarator
Examples of incorrect code for this rule with the 2, { "VariableDeclarator": 1 }
options:
/*eslint indent: ["error", 2, { "VariableDeclarator": 1 }]*/
/*eslint-env es6*/
var a,
b,
c;
let a,
b,
c;
const a = 1,
b = 2,
c = 3;
Examples of correct code for this rule with the 2, { "VariableDeclarator": 1 }
options:
/*eslint indent: ["error", 2, { "VariableDeclarator": 1 }]*/
/*eslint-env es6*/
var a,
b,
c;
let a,
b,
c;
const a = 1,
b = 2,
c = 3;
Examples of correct code for this rule with the 2, { "VariableDeclarator": 2 }
options:
/*eslint indent: ["error", 2, { "VariableDeclarator": 2 }]*/
/*eslint-env es6*/
var a,
b,
c;
let a,
b,
c;
const a = 1,
b = 2,
c = 3;
Examples of correct code for this rule with the 2, { "VariableDeclarator": { "var": 2, "let": 2, "const": 3 } }
options:
/*eslint indent: ["error", 2, { "VariableDeclarator": { "var": 2, "let": 2, "const": 3 } }]*/
/*eslint-env es6*/
var a,
b,
c;
let a,
b,
c;
const a = 1,
b = 2,
c = 3;
outerIIFEBody
Examples of incorrect code for this rule with the options 2, { "outerIIFEBody": 0 }
:
/*eslint indent: ["error", 2, { "outerIIFEBody": 0 }]*/
(function() {
function foo(x) {
return x + 1;
}
})();
if(y) {
console.log('foo');
}
Examples of correct code for this rule with the options 2, {"outerIIFEBody": 0}
:
/*eslint indent: ["error", 2, { "outerIIFEBody": 0 }]*/
(function() {
function foo(x) {
return x + 1;
}
})();
if(y) {
console.log('foo');
}
MemberExpression
Examples of incorrect code for this rule with the 2, { "MemberExpression": 1 }
options:
/*eslint indent: ["error", 2, { "MemberExpression": 1 }]*/
foo
.bar
.baz()
Examples of correct code for this rule with the 2, { "MemberExpression": 1 }
option:
/*eslint indent: ["error", 2, { "MemberExpression": 1 }]*/
foo
.bar
.baz();
// Any indentation is permitted in variable declarations and assignments.
var bip = aardvark.badger
.coyote;
FunctionDeclaration
Examples of incorrect code for this rule with the 2, { "FunctionDeclaration": {"body": 1, "parameters": 2} }
option:
/*eslint indent: ["error", 2, { "FunctionDeclaration": {"body": 1, "parameters": 2} }]*/
function foo(bar,
baz,
qux) {
qux();
}
Examples of correct code for this rule with the 2, { "FunctionDeclaration": {"body": 1, "parameters": 2} }
option:
/*eslint indent: ["error", 2, { "FunctionDeclaration": {"body": 1, "parameters": 2} }]*/
function foo(bar,
baz,
qux) {
qux();
}
Examples of incorrect code for this rule with the 2, { "FunctionDeclaration": {"parameters": "first"} }
option:
/*eslint indent: ["error", 2, {"FunctionDeclaration": {"parameters": "first"}}]*/
function foo(bar, baz,
qux, boop) {
qux();
}
Examples of correct code for this rule with the 2, { "FunctionDeclaration": {"parameters": "first"} }
option:
/*eslint indent: ["error", 2, {"FunctionDeclaration": {"parameters": "first"}}]*/
function foo(bar, baz,
qux, boop) {
qux();
}
FunctionExpression
Examples of incorrect code for this rule with the 2, { "FunctionExpression": {"body": 1, "parameters": 2} }
option:
/*eslint indent: ["error", 2, { "FunctionExpression": {"body": 1, "parameters": 2} }]*/
var foo = function(bar,
baz,
qux) {
qux();
}
Examples of correct code for this rule with the 2, { "FunctionExpression": {"body": 1, "parameters": 2} }
option:
/*eslint indent: ["error", 2, { "FunctionExpression": {"body": 1, "parameters": 2} }]*/
var foo = function(bar,
baz,
qux) {
qux();
}
Examples of incorrect code for this rule with the 2, { "FunctionExpression": {"parameters": "first"} }
option:
/*eslint indent: ["error", 2, {"FunctionExpression": {"parameters": "first"}}]*/
var foo = function(bar, baz,
qux, boop) {
qux();
}
Examples of correct code for this rule with the 2, { "FunctionExpression": {"parameters": "first"} }
option:
/*eslint indent: ["error", 2, {"FunctionExpression": {"parameters": "first"}}]*/
var foo = function(bar, baz,
qux, boop) {
qux();
}
CallExpression
Examples of incorrect code for this rule with the 2, { "CallExpression": {"arguments": 1} }
option:
/*eslint indent: ["error", 2, { "CallExpression": {"arguments": 1} }]*/
foo(bar,
baz,
qux
);
Examples of correct code for this rule with the 2, { "CallExpression": {"arguments": 1} }
option:
/*eslint indent: ["error", 2, { "CallExpression": {"arguments": 1} }]*/
foo(bar,
baz,
qux
);
Examples of incorrect code for this rule with the 2, { "CallExpression": {"arguments": "first"} }
option:
/*eslint indent: ["error", 2, {"CallExpression": {"arguments": "first"}}]*/
foo(bar, baz,
baz, boop, beep);
Examples of correct code for this rule with the 2, { "CallExpression": {"arguments": "first"} }
option:
/*eslint indent: ["error", 2, {"CallExpression": {"arguments": "first"}}]*/
foo(bar, baz,
baz, boop, beep);
ArrayExpression
Examples of incorrect code for this rule with the 2, { "ArrayExpression": 1 }
option:
/*eslint indent: ["error", 2, { "ArrayExpression": 1 }]*/
var foo = [
bar,
baz,
qux
];
Examples of correct code for this rule with the 2, { "ArrayExpression": 1 }
option:
/*eslint indent: ["error", 2, { "ArrayExpression": 1 }]*/
var foo = [
bar,
baz,
qux
];
Examples of incorrect code for this rule with the 2, { "ArrayExpression": "first" }
option:
/*eslint indent: ["error", 2, {"ArrayExpression": "first"}]*/
var foo = [bar,
baz,
qux
];
Examples of correct code for this rule with the 2, { "ArrayExpression": "first" }
option:
/*eslint indent: ["error", 2, {"ArrayExpression": "first"}]*/
var foo = [bar,
baz,
qux
];
ObjectExpression
Examples of incorrect code for this rule with the 2, { "ObjectExpression": 1 }
option:
/*eslint indent: ["error", 2, { "ObjectExpression": 1 }]*/
var foo = {
bar: 1,
baz: 2,
qux: 3
};
Examples of correct code for this rule with the 2, { "ObjectExpression": 1 }
option:
/*eslint indent: ["error", 2, { "ObjectExpression": 1 }]*/
var foo = {
bar: 1,
baz: 2,
qux: 3
};
Examples of incorrect code for this rule with the 2, { "ObjectExpression": "first" }
option:
/*eslint indent: ["error", 2, {"ObjectExpression": "first"}]*/
var foo = { bar: 1,
baz: 2 };
Examples of correct code for this rule with the 2, { "ObjectExpression": "first" }
option:
/*eslint indent: ["error", 2, {"ObjectExpression": "first"}]*/
var foo = { bar: 1,
baz: 2 };
Compatibility
-
JSHint:
indent
- JSCS: validateIndentation Source: http://eslint.org/docs/rules/
Expected linebreaks to be 'LF' but found 'CRLF'. Open
- Read upRead up
- Exclude checks
enforce consistent linebreak style (linebreak-style)
When developing with a lot of people all having different editors, VCS applications and operating systems it may occur that different line endings are written by either of the mentioned (might especially happen when using the windows and mac versions of SourceTree together).
The linebreaks (new lines) used in windows operating system are usually carriage returns (CR) followed by a line feed (LF) making it a carriage return line feed (CRLF)
whereas Linux and Unix use a simple line feed (LF). The corresponding control sequences are "\n"
(for LF) and "\r\n"
for (CRLF).
Many versioning systems (like git and subversion) can automatically ensure the correct ending. However to cover all contingencies, you can activate this rule.
Rule Details
This rule enforces consistent line endings independent of operating system, VCS, or editor used across your codebase.
Options
This rule has a string option:
-
"unix"
(default) enforces the usage of Unix line endings:\n
for LF. -
"windows"
enforces the usage of Windows line endings:\r\n
for CRLF.
unix
Examples of incorrect code for this rule with the default "unix"
option:
/*eslint linebreak-style: ["error", "unix"]*/
var a = 'a'; // \r\n
Examples of correct code for this rule with the default "unix"
option:
/*eslint linebreak-style: ["error", "unix"]*/
var a = 'a', // \n
b = 'b'; // \n
// \n
function foo(params) { // \n
// do stuff \n
}// \n
windows
Examples of incorrect code for this rule with the "windows"
option:
/*eslint linebreak-style: ["error", "windows"]*/
var a = 'a'; // \n
Examples of correct code for this rule with the "windows"
option:
/*eslint linebreak-style: ["error", "windows"]*/
var a = 'a', // \r\n
b = 'b'; // \r\n
// \r\n
function foo(params) { // \r\n
// do stuff \r\n
} // \r\n
Using this rule with version control systems
Version control systems sometimes have special behavior for linebreaks. To make it easy for developers to contribute to your codebase from different platforms, you may want to configure your VCS to handle linebreaks appropriately.
For example, the default behavior of git on Windows systems is to convert LF linebreaks to CRLF when checking out files, but to store the linebreaks as LF when committing a change. This will cause the linebreak-style
rule to report errors if configured with the "unix"
setting, because the files that ESLint sees will have CRLF linebreaks. If you use git, you may want to add a line to your .gitattributes
file to prevent git from converting linebreaks in .js
files:
*.js text eol=lf
When Not To Use It
If you aren't concerned about having different line endings within your code, then you can safely turn this rule off.
Compatibility
- JSCS: validateLineBreaks Source: http://eslint.org/docs/rules/
Expected linebreaks to be 'LF' but found 'CRLF'. Open
}
- Read upRead up
- Exclude checks
enforce consistent linebreak style (linebreak-style)
When developing with a lot of people all having different editors, VCS applications and operating systems it may occur that different line endings are written by either of the mentioned (might especially happen when using the windows and mac versions of SourceTree together).
The linebreaks (new lines) used in windows operating system are usually carriage returns (CR) followed by a line feed (LF) making it a carriage return line feed (CRLF)
whereas Linux and Unix use a simple line feed (LF). The corresponding control sequences are "\n"
(for LF) and "\r\n"
for (CRLF).
Many versioning systems (like git and subversion) can automatically ensure the correct ending. However to cover all contingencies, you can activate this rule.
Rule Details
This rule enforces consistent line endings independent of operating system, VCS, or editor used across your codebase.
Options
This rule has a string option:
-
"unix"
(default) enforces the usage of Unix line endings:\n
for LF. -
"windows"
enforces the usage of Windows line endings:\r\n
for CRLF.
unix
Examples of incorrect code for this rule with the default "unix"
option:
/*eslint linebreak-style: ["error", "unix"]*/
var a = 'a'; // \r\n
Examples of correct code for this rule with the default "unix"
option:
/*eslint linebreak-style: ["error", "unix"]*/
var a = 'a', // \n
b = 'b'; // \n
// \n
function foo(params) { // \n
// do stuff \n
}// \n
windows
Examples of incorrect code for this rule with the "windows"
option:
/*eslint linebreak-style: ["error", "windows"]*/
var a = 'a'; // \n
Examples of correct code for this rule with the "windows"
option:
/*eslint linebreak-style: ["error", "windows"]*/
var a = 'a', // \r\n
b = 'b'; // \r\n
// \r\n
function foo(params) { // \r\n
// do stuff \r\n
} // \r\n
Using this rule with version control systems
Version control systems sometimes have special behavior for linebreaks. To make it easy for developers to contribute to your codebase from different platforms, you may want to configure your VCS to handle linebreaks appropriately.
For example, the default behavior of git on Windows systems is to convert LF linebreaks to CRLF when checking out files, but to store the linebreaks as LF when committing a change. This will cause the linebreak-style
rule to report errors if configured with the "unix"
setting, because the files that ESLint sees will have CRLF linebreaks. If you use git, you may want to add a line to your .gitattributes
file to prevent git from converting linebreaks in .js
files:
*.js text eol=lf
When Not To Use It
If you aren't concerned about having different line endings within your code, then you can safely turn this rule off.
Compatibility
- JSCS: validateLineBreaks Source: http://eslint.org/docs/rules/
Expected linebreaks to be 'LF' but found 'CRLF'. Open
- Read upRead up
- Exclude checks
enforce consistent linebreak style (linebreak-style)
When developing with a lot of people all having different editors, VCS applications and operating systems it may occur that different line endings are written by either of the mentioned (might especially happen when using the windows and mac versions of SourceTree together).
The linebreaks (new lines) used in windows operating system are usually carriage returns (CR) followed by a line feed (LF) making it a carriage return line feed (CRLF)
whereas Linux and Unix use a simple line feed (LF). The corresponding control sequences are "\n"
(for LF) and "\r\n"
for (CRLF).
Many versioning systems (like git and subversion) can automatically ensure the correct ending. However to cover all contingencies, you can activate this rule.
Rule Details
This rule enforces consistent line endings independent of operating system, VCS, or editor used across your codebase.
Options
This rule has a string option:
-
"unix"
(default) enforces the usage of Unix line endings:\n
for LF. -
"windows"
enforces the usage of Windows line endings:\r\n
for CRLF.
unix
Examples of incorrect code for this rule with the default "unix"
option:
/*eslint linebreak-style: ["error", "unix"]*/
var a = 'a'; // \r\n
Examples of correct code for this rule with the default "unix"
option:
/*eslint linebreak-style: ["error", "unix"]*/
var a = 'a', // \n
b = 'b'; // \n
// \n
function foo(params) { // \n
// do stuff \n
}// \n
windows
Examples of incorrect code for this rule with the "windows"
option:
/*eslint linebreak-style: ["error", "windows"]*/
var a = 'a'; // \n
Examples of correct code for this rule with the "windows"
option:
/*eslint linebreak-style: ["error", "windows"]*/
var a = 'a', // \r\n
b = 'b'; // \r\n
// \r\n
function foo(params) { // \r\n
// do stuff \r\n
} // \r\n
Using this rule with version control systems
Version control systems sometimes have special behavior for linebreaks. To make it easy for developers to contribute to your codebase from different platforms, you may want to configure your VCS to handle linebreaks appropriately.
For example, the default behavior of git on Windows systems is to convert LF linebreaks to CRLF when checking out files, but to store the linebreaks as LF when committing a change. This will cause the linebreak-style
rule to report errors if configured with the "unix"
setting, because the files that ESLint sees will have CRLF linebreaks. If you use git, you may want to add a line to your .gitattributes
file to prevent git from converting linebreaks in .js
files:
*.js text eol=lf
When Not To Use It
If you aren't concerned about having different line endings within your code, then you can safely turn this rule off.
Compatibility
- JSCS: validateLineBreaks Source: http://eslint.org/docs/rules/
Expected linebreaks to be 'LF' but found 'CRLF'. Open
- Read upRead up
- Exclude checks
enforce consistent linebreak style (linebreak-style)
When developing with a lot of people all having different editors, VCS applications and operating systems it may occur that different line endings are written by either of the mentioned (might especially happen when using the windows and mac versions of SourceTree together).
The linebreaks (new lines) used in windows operating system are usually carriage returns (CR) followed by a line feed (LF) making it a carriage return line feed (CRLF)
whereas Linux and Unix use a simple line feed (LF). The corresponding control sequences are "\n"
(for LF) and "\r\n"
for (CRLF).
Many versioning systems (like git and subversion) can automatically ensure the correct ending. However to cover all contingencies, you can activate this rule.
Rule Details
This rule enforces consistent line endings independent of operating system, VCS, or editor used across your codebase.
Options
This rule has a string option:
-
"unix"
(default) enforces the usage of Unix line endings:\n
for LF. -
"windows"
enforces the usage of Windows line endings:\r\n
for CRLF.
unix
Examples of incorrect code for this rule with the default "unix"
option:
/*eslint linebreak-style: ["error", "unix"]*/
var a = 'a'; // \r\n
Examples of correct code for this rule with the default "unix"
option:
/*eslint linebreak-style: ["error", "unix"]*/
var a = 'a', // \n
b = 'b'; // \n
// \n
function foo(params) { // \n
// do stuff \n
}// \n
windows
Examples of incorrect code for this rule with the "windows"
option:
/*eslint linebreak-style: ["error", "windows"]*/
var a = 'a'; // \n
Examples of correct code for this rule with the "windows"
option:
/*eslint linebreak-style: ["error", "windows"]*/
var a = 'a', // \r\n
b = 'b'; // \r\n
// \r\n
function foo(params) { // \r\n
// do stuff \r\n
} // \r\n
Using this rule with version control systems
Version control systems sometimes have special behavior for linebreaks. To make it easy for developers to contribute to your codebase from different platforms, you may want to configure your VCS to handle linebreaks appropriately.
For example, the default behavior of git on Windows systems is to convert LF linebreaks to CRLF when checking out files, but to store the linebreaks as LF when committing a change. This will cause the linebreak-style
rule to report errors if configured with the "unix"
setting, because the files that ESLint sees will have CRLF linebreaks. If you use git, you may want to add a line to your .gitattributes
file to prevent git from converting linebreaks in .js
files:
*.js text eol=lf
When Not To Use It
If you aren't concerned about having different line endings within your code, then you can safely turn this rule off.
Compatibility
- JSCS: validateLineBreaks Source: http://eslint.org/docs/rules/
Missing JSDoc for parameter 'value'. Open
/**
- Read upRead up
- Exclude checks
enforce valid JSDoc comments (valid-jsdoc)
JSDoc generates application programming interface (API) documentation from specially-formatted comments in JavaScript code. For example, this is a JSDoc comment for a function:
/**
* Add two numbers.
* @param {number} num1 The first number.
* @param {number} num2 The second number.
* @returns {number} The sum of the two numbers.
*/
function add(num1, num2) {
return num1 + num2;
}
If comments are invalid because of typing mistakes, then documentation will be incomplete.
If comments are inconsistent because they are not updated when function definitions are modified, then readers might become confused.
Rule Details
This rule enforces valid and consistent JSDoc comments. It reports any of the following problems:
- missing parameter tag:
@arg
,@argument
, or@param
- inconsistent order of parameter names in a comment compared to the function or method
- missing return tag:
@return
or@returns
- missing parameter or return type
- missing parameter or return description
- syntax error
This rule does not report missing JSDoc comments for classes, functions, or methods.
Note: This rule does not support all of the Google Closure documentation tool's use cases. As such, some code such as (/**number*/ n => n * 2);
will be flagged as missing appropriate function JSDoc comments even though /**number*/
is intended to be a type hint and not a documentation block for the function. We don't recommend using this rule if you use type hints in this way.
Examples of incorrect code for this rule:
/*eslint valid-jsdoc: "error"*/
// expected @param tag for parameter num1 but found num instead
// missing @param tag for parameter num2
// missing return type
/**
* Add two numbers.
* @param {number} num The first number.
* @returns The sum of the two numbers.
*/
function add(num1, num2) {
return num1 + num2;
}
// missing brace
// missing @returns tag
/**
* @param {string name Whom to greet.
*/
function greet(name) {
console.log("Hello " + name);
}
// missing parameter type for num1
// missing parameter description for num2
/**
* Represents a sum.
* @constructor
* @param num1 The first number.
* @param {number} num2
*/
function sum(num1, num2) {
this.num1 = num1;
this.num2 = num2;
}
Examples of correct code for this rule:
/*eslint valid-jsdoc: "error"*/
/*eslint-env es6*/
/**
* Add two numbers.
* @param {number} num1 The first number.
* @param {number} num2 The second number.
* @returns {number} The sum of the two numbers.
*/
function add(num1, num2) {
return num1 + num2;
}
// default options allow missing function description
// return type `void` means the function has no `return` statement
/**
* @param {string} name Whom to greet.
* @returns {void}
*/
function greet(name) {
console.log("Hello " + name);
}
// @constructor tag allows missing @returns tag
/**
* Represents a sum.
* @constructor
* @param {number} num1 The first number.
* @param {number} num2 The second number.
*/
function sum(num1, num2) {
this.num1 = num1;
this.num2 = num2;
}
// class constructor allows missing @returns tag
/**
* Represents a sum.
*/
class Sum {
/**
* @param {number} num1 The first number.
* @param {number} num2 The second number.
*/
constructor(num1, num2) {
this.num1 = num1;
this.num2 = num2;
}
}
// @abstract tag allows @returns tag without `return` statement
class Widget {
/**
* When the state changes, does it affect the rendered appearance?
* @abstract
* @param {Object} state The new state of the widget.
* @returns {boolean} Is current appearance inconsistent with new state?
*/
mustRender (state) {
throw new Error("Widget subclass did not implement mustRender");
}
}
// @override tag allows missing @param and @returns tags
class WonderfulWidget extends Widget {
/**
* @override
*/
mustRender (state) {
return state !== this.state; // shallow comparison
}
}
Options
This rule has an object option:
-
"prefer"
enforces consistent documentation tags specified by an object whose properties mean instead of key use value (for example,"return": "returns"
means instead of@return
use@returns
) -
"preferType"
enforces consistent type strings specified by an object whose properties mean instead of key use value (for example,"object": "Object"
means instead ofobject
useObject
) -
"requireReturn"
requires a return tag:-
true
(default) even if the function or method does not have areturn
statement (this option value does not apply to constructors) -
false
if and only if the function or method has areturn
statement (this option value does apply to constructors)
-
-
"requireReturnType": false
allows missing type in return tags -
"matchDescription"
specifies (as a string) a regular expression to match the description in each JSDoc comment (for example,".+"
requires a description; this option does not apply to descriptions in parameter or return tags) -
"requireParamDescription": false
allows missing description in parameter tags -
"requireReturnDescription": false
allows missing description in return tags
prefer
Examples of additional incorrect code for this rule with sample "prefer": { "arg": "param", "argument": "param", "class": "constructor", "return": "returns", "virtual": "abstract" }
options:
/*eslint valid-jsdoc: ["error", { "prefer": { "arg": "param", "argument": "param", "class": "constructor", "return": "returns", "virtual": "abstract" } }]*/
/*eslint-env es6*/
/**
* Add two numbers.
* @arg {int} num1 The first number.
* @arg {int} num2 The second number.
* @return {int} The sum of the two numbers.
*/
function add(num1, num2) {
return num1 + num2;
}
/**
* Represents a sum.
* @class
* @argument {number} num1 The first number.
* @argument {number} num2 The second number.
*/
function sum(num1, num2) {
this.num1 = num1;
this.num2 = num2;
}
class Widget {
/**
* When the state changes, does it affect the rendered appearance?
* @virtual
* @argument {Object} state The new state of the widget.
* @return {boolean} Is current appearance inconsistent with new state?
*/
mustRender (state) {
throw new Error("Widget subclass did not implement mustRender");
}
}
preferType
Examples of additional incorrect code for this rule with sample "preferType": { "Boolean": "boolean", "Number": "number", "object": "Object", "String": "string" }
options:
/*eslint valid-jsdoc: ["error", { "preferType": { "Boolean": "boolean", "Number": "number", "object": "Object", "String": "string" } }]*/
/*eslint-env es6*/
/**
* Add two numbers.
* @param {Number} num1 The first number.
* @param {Number} num2 The second number.
* @returns {Number} The sum of the two numbers.
*/
function add(num1, num2) {
return num1 + num2;
}
/**
* Output a greeting as a side effect.
* @param {String} name Whom to greet.
* @returns {void}
*/
function greet(name) {
console.log("Hello " + name);
}
class Widget {
/**
* When the state changes, does it affect the rendered appearance?
* @abstract
* @param {object} state The new state of the widget.
* @returns {Boolean} Is current appearance inconsistent with new state?
*/
mustRender (state) {
throw new Error("Widget subclass did not implement mustRender");
}
}
requireReturn
Examples of additional incorrect code for this rule with the "requireReturn": false
option:
/*eslint valid-jsdoc: ["error", { "requireReturn": false }]*/
// unexpected @returns tag because function has no `return` statement
/**
* @param {string} name Whom to greet.
* @returns {string} The greeting.
*/
function greet(name) {
console.log("Hello " + name);
}
// add @abstract tag to allow @returns tag without `return` statement
class Widget {
/**
* When the state changes, does it affect the rendered appearance?
* @param {Object} state The new state of the widget.
* @returns {boolean} Is current appearance inconsistent with new state?
*/
mustRender (state) {
throw new Error("Widget subclass did not implement mustRender");
}
}
Example of additional correct code for this rule with the "requireReturn": false
option:
/*eslint valid-jsdoc: ["error", { "requireReturn": false }]*/
/**
* @param {string} name Whom to greet.
*/
function greet(name) {
console.log("Hello " + name);
}
requireReturnType
Example of additional correct code for this rule with the "requireReturnType": false
option:
/*eslint valid-jsdoc: ["error", { "requireReturnType": false }]*/
/**
* Add two numbers.
* @param {number} num1 The first number.
* @param {number} num2 The second number.
* @returns The sum of the two numbers.
*/
function add(num1, num2) {
return num1 + num2;
}
matchDescription
Example of additional incorrect code for this rule with a sample "matchDescription": ".+"
option:
/*eslint valid-jsdoc: ["error", { "matchDescription": ".+" }]*/
// missing function description
/**
* @param {string} name Whom to greet.
* @returns {void}
*/
function greet(name) {
console.log("Hello " + name);
}
requireParamDescription
Example of additional correct code for this rule with the "requireParamDescription": false
option:
/*eslint valid-jsdoc: ["error", { "requireParamDescription": false }]*/
/**
* Add two numbers.
* @param {int} num1
* @param {int} num2
* @returns {int} The sum of the two numbers.
*/
function add(num1, num2) {
return num1 + num2;
}
requireReturnDescription
Example of additional correct code for this rule with the "requireReturnDescription": false
option:
/*eslint valid-jsdoc: ["error", { "requireReturnDescription": false }]*/
/**
* Add two numbers.
* @param {number} num1 The first number.
* @param {number} num2 The second number.
* @returns {number}
*/
function add(num1, num2) {
return num1 + num2;
}
When Not To Use It
If you aren't using JSDoc, then you can safely turn this rule off.
Further Reading
Related Rules
- [require-jsdoc](require-jsdoc.md) Source: http://eslint.org/docs/rules/
'sound' is assigned a value but never used. Open
function notify_success(title, message = '<%= file.relative %>', onLast = false, sound = false) {
- 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/
Missing JSDoc comment. Open
function notify_end(title, sound = false) {
- 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/
There should be no space after '{'. Open
.pipe($.plumber({ errorHandler: notify_error('webpack') }))
- Read upRead up
- Exclude checks
enforce consistent spacing inside braces (object-curly-spacing)
While formatting preferences are very personal, a number of style guides require or disallow spaces between curly braces in the following situations:
// simple object literals
var obj = { foo: "bar" };
// nested object literals
var obj = { foo: { zoo: "bar" } };
// destructuring assignment (EcmaScript 6)
var { x, y } = y;
// import/export declarations (EcmaScript 6)
import { foo } from "bar";
export { foo };
Rule Details
This rule enforce consistent spacing inside braces of object literals, destructuring assignments, and import/export specifiers.
Options
This rule has two options, a string option and an object option.
String option:
-
"never"
(default) disallows spacing inside of braces -
"always"
requires spacing inside of braces (except{}
)
Object option:
-
"arraysInObjects": true
requires spacing inside of braces of objects beginning and/or ending with an array element (applies when the first option is set tonever
) -
"arraysInObjects": false
disallows spacing inside of braces of objects beginning and/or ending with an array element (applies when the first option is set toalways
) -
"objectsInObjects": true
requires spacing inside of braces of objects beginning and/or ending with an object element (applies when the first option is set tonever
) -
"objectsInObjects": false
disallows spacing inside of braces of objects beginning and/or ending with an object element (applies when the first option is set toalways
)
never
Examples of incorrect code for this rule with the default "never"
option:
/*eslint object-curly-spacing: ["error", "never"]*/
var obj = { 'foo': 'bar' };
var obj = {'foo': 'bar' };
var obj = { baz: {'foo': 'qux'}, bar};
var obj = {baz: { 'foo': 'qux'}, bar};
var {x } = y;
import { foo } from 'bar';
Examples of correct code for this rule with the default "never"
option:
/*eslint object-curly-spacing: ["error", "never"]*/
var obj = {'foo': 'bar'};
var obj = {'foo': {'bar': 'baz'}, 'qux': 'quxx'};
var obj = {
'foo': 'bar'
};
var obj = {'foo': 'bar'
};
var obj = {
'foo':'bar'};
var obj = {};
var {x} = y;
import {foo} from 'bar';
always
Examples of incorrect code for this rule with the "always"
option:
/*eslint object-curly-spacing: ["error", "always"]*/
var obj = {'foo': 'bar'};
var obj = {'foo': 'bar' };
var obj = { baz: {'foo': 'qux'}, bar};
var obj = {baz: { 'foo': 'qux' }, bar};
var obj = {'foo': 'bar'
};
var obj = {
'foo':'bar'};
var {x} = y;
import {foo } from 'bar';
Examples of correct code for this rule with the "always"
option:
/*eslint object-curly-spacing: ["error", "always"]*/
var obj = {};
var obj = { 'foo': 'bar' };
var obj = { 'foo': { 'bar': 'baz' }, 'qux': 'quxx' };
var obj = {
'foo': 'bar'
};
var { x } = y;
import { foo } from 'bar';
arraysInObjects
Examples of additional correct code for this rule with the "never", { "arraysInObjects": true }
options:
/*eslint object-curly-spacing: ["error", "never", { "arraysInObjects": true }]*/
var obj = {"foo": [ 1, 2 ] };
var obj = {"foo": [ "baz", "bar" ] };
Examples of additional correct code for this rule with the "always", { "arraysInObjects": false }
options:
/*eslint object-curly-spacing: ["error", "always", { "arraysInObjects": false }]*/
var obj = { "foo": [ 1, 2 ]};
var obj = { "foo": [ "baz", "bar" ]};
objectsInObjects
Examples of additional correct code for this rule with the "never", { "objectsInObjects": true }
options:
/*eslint object-curly-spacing: ["error", "never", { "objectsInObjects": true }]*/
var obj = {"foo": {"baz": 1, "bar": 2} };
Examples of additional correct code for this rule with the "always", { "objectsInObjects": false }
options:
/*eslint object-curly-spacing: ["error", "always", { "objectsInObjects": false }]*/
var obj = { "foo": { "baz": 1, "bar": 2 }};
When Not To Use It
You can turn this rule off if you are not concerned with the consistency of spacing between curly braces.
Related Rules
- [comma-spacing](comma-spacing.md)
- [space-in-parens](space-in-parens.md) Source: http://eslint.org/docs/rules/
Unexpected function expression. Open
gulp.task('lint-fix', function() {
- Read upRead up
- Exclude checks
Suggest using arrow functions as callbacks. (prefer-arrow-callback)
Arrow functions are suited to callbacks, because:
-
this
keywords in arrow functions bind to the upper scope's. - The notation of the arrow function is shorter than function expression's.
Rule Details
This rule is aimed to flag usage of function expressions in an argument list.
The following patterns are considered problems:
/*eslint prefer-arrow-callback: "error"*/
foo(function(a) { return a; });
foo(function() { return this.a; }.bind(this));
The following patterns are not considered problems:
/*eslint prefer-arrow-callback: "error"*/
/*eslint-env es6*/
foo(a => a);
foo(function*() { yield; });
// this is not a callback.
var foo = function foo(a) { return a; };
// using `this` without `.bind(this)`.
foo(function() { return this.a; });
// recursively.
foo(function bar(n) { return n && n + bar(n - 1); });
Options
This rule takes one optional argument, an object which is an options object.
allowNamedFunctions
This is a boolean
option and it is false
by default. When set to true
, the rule doesn't warn on named functions used as callbacks.
Examples of correct code for the { "allowNamedFunctions": true }
option:
/*eslint prefer-arrow-callback: ["error", { "allowNamedFunctions": true }]*/
foo(function bar() {});
allowUnboundThis
This is a boolean
option and it is true
by default. When set to false
, this option allows the use of this
without restriction and checks for dynamically assigned this
values such as when using Array.prototype.map
with a context
argument. Normally, the rule will flag the use of this
whenever a function does not use bind()
to specify the value of this
constantly.
Examples of incorrect code for the { "allowUnboundThis": false }
option:
/*eslint prefer-arrow-callback: ["error", { "allowUnboundThis": false }]*/
/*eslint-env es6*/
foo(function() { this.a; });
foo(function() { (() => this); });
someArray.map(function (itm) { return this.doSomething(itm); }, someObject);
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 function expressions in an argument list, you can safely disable this rule. Source: http://eslint.org/docs/rules/
Unexpected function expression. Open
gulp.task('doc', ['clean-doc'], function() {
- Read upRead up
- Exclude checks
Suggest using arrow functions as callbacks. (prefer-arrow-callback)
Arrow functions are suited to callbacks, because:
-
this
keywords in arrow functions bind to the upper scope's. - The notation of the arrow function is shorter than function expression's.
Rule Details
This rule is aimed to flag usage of function expressions in an argument list.
The following patterns are considered problems:
/*eslint prefer-arrow-callback: "error"*/
foo(function(a) { return a; });
foo(function() { return this.a; }.bind(this));
The following patterns are not considered problems:
/*eslint prefer-arrow-callback: "error"*/
/*eslint-env es6*/
foo(a => a);
foo(function*() { yield; });
// this is not a callback.
var foo = function foo(a) { return a; };
// using `this` without `.bind(this)`.
foo(function() { return this.a; });
// recursively.
foo(function bar(n) { return n && n + bar(n - 1); });
Options
This rule takes one optional argument, an object which is an options object.
allowNamedFunctions
This is a boolean
option and it is false
by default. When set to true
, the rule doesn't warn on named functions used as callbacks.
Examples of correct code for the { "allowNamedFunctions": true }
option:
/*eslint prefer-arrow-callback: ["error", { "allowNamedFunctions": true }]*/
foo(function bar() {});
allowUnboundThis
This is a boolean
option and it is true
by default. When set to false
, this option allows the use of this
without restriction and checks for dynamically assigned this
values such as when using Array.prototype.map
with a context
argument. Normally, the rule will flag the use of this
whenever a function does not use bind()
to specify the value of this
constantly.
Examples of incorrect code for the { "allowUnboundThis": false }
option:
/*eslint prefer-arrow-callback: ["error", { "allowUnboundThis": false }]*/
/*eslint-env es6*/
foo(function() { this.a; });
foo(function() { (() => this); });
someArray.map(function (itm) { return this.doSomething(itm); }, someObject);
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 function expressions in an argument list, you can safely disable this rule. Source: http://eslint.org/docs/rules/
No magic number: 0. Open
if (chrome_index >= 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/
Missing space before opening brace. Open
export default function mixinClass(baseClass, target){
- Read upRead up
- Exclude checks
Require Or Disallow Space Before Blocks (space-before-blocks)
Consistency is an important part of any style guide. While it is a personal preference where to put the opening brace of blocks, it should be consistent across a whole project. Having an inconsistent style distracts the reader from seeing the important parts of the code.
Rule Details
This rule will enforce consistency of spacing before blocks. It is only applied on blocks that don’t begin on a new line.
- This rule ignores spacing which is between
=>
and a block. The spacing is handled by thearrow-spacing
rule. - This rule ignores spacing which is between a keyword and a block. The spacing is handled by the
keyword-spacing
rule.
Options
This rule takes one argument. If it is "always"
then blocks must always have at least one preceding space. If "never"
then all blocks should never have any preceding space. If different spacing is desired for function
blocks, keyword blocks and classes, an optional configuration object can be passed as the rule argument to
configure the cases separately.
( e.g. { "functions": "never", "keywords": "always", "classes": "always" }
)
The default is "always"
.
"always"
Examples of incorrect code for this rule with the "always" option:
/*eslint space-before-blocks: "error"*/
if (a){
b();
}
function a(){}
for (;;){
b();
}
try {} catch(a){}
class Foo{
constructor(){}
}
Examples of correct code for this rule with the "always" option:
/*eslint space-before-blocks: "error"*/
if (a) {
b();
}
if (a) {
b();
} else{ /*no error. this is checked by `keyword-spacing` rule.*/
c();
}
function a() {}
for (;;) {
b();
}
try {} catch(a) {}
"never"
Examples of incorrect code for this rule with the "never" option:
/*eslint space-before-blocks: ["error", "never"]*/
if (a) {
b();
}
function a() {}
for (;;) {
b();
}
try {} catch(a) {}
Examples of correct code for this rule with the "never" option:
/*eslint space-before-blocks: ["error", "never"]*/
if (a){
b();
}
function a(){}
for (;;){
b();
}
try{} catch(a){}
class Foo{
constructor(){}
}
Examples of incorrect code for this rule when configured { "functions": "never", "keywords": "always", "classes": "never" }
:
/*eslint space-before-blocks: ["error", { "functions": "never", "keywords": "always", "classes": "never" }]*/
/*eslint-env es6*/
function a() {}
try {} catch(a){}
class Foo{
constructor() {}
}
Examples of correct code for this rule when configured { "functions": "never", "keywords": "always", "classes": "never" }
:
/*eslint space-before-blocks: ["error", { "functions": "never", "keywords": "always", "classes": "never" }]*/
/*eslint-env es6*/
for (;;) {
// ...
}
describe(function(){
// ...
});
class Foo {
constructor(){}
}
Examples of incorrect code for this rule when configured { "functions": "always", "keywords": "never", "classes": "never" }
:
/*eslint space-before-blocks: ["error", { "functions": "always", "keywords": "never", "classes": "never" }]*/
/*eslint-env es6*/
function a(){}
try {} catch(a) {}
class Foo {
constructor(){}
}
Examples of correct code for this rule when configured { "functions": "always", "keywords": "never", "classes": "never" }
:
/*eslint space-before-blocks: ["error", { "functions": "always", "keywords": "never", "classes": "never" }]*/
/*eslint-env es6*/
if (a){
b();
}
var a = function() {}
class Foo{
constructor() {}
}
Examples of incorrect code for this rule when configured { "functions": "never", "keywords": "never", "classes": "always" }
:
/*eslint space-before-blocks: ["error", { "functions": "never", "keywords": "never", "classes": "always" }]*/
/*eslint-env es6*/
class Foo{
constructor(){}
}
Examples of correct code for this rule when configured { "functions": "never", "keywords": "never", "classes": "always" }
:
/*eslint space-before-blocks: ["error", { "functions": "never", "keywords": "never", "classes": "always" }]*/
/*eslint-env es6*/
class Foo {
constructor(){}
}
When Not To Use It
You can turn this rule off if you are not concerned with the consistency of spacing before blocks.
Related Rules
- [keyword-spacing](keyword-spacing.md)
- [arrow-spacing](arrow-spacing.md)
- [brace-style](brace-style.md) Source: http://eslint.org/docs/rules/
Expected linebreaks to be 'LF' but found 'CRLF'. Open
- Read upRead up
- Exclude checks
enforce consistent linebreak style (linebreak-style)
When developing with a lot of people all having different editors, VCS applications and operating systems it may occur that different line endings are written by either of the mentioned (might especially happen when using the windows and mac versions of SourceTree together).
The linebreaks (new lines) used in windows operating system are usually carriage returns (CR) followed by a line feed (LF) making it a carriage return line feed (CRLF)
whereas Linux and Unix use a simple line feed (LF). The corresponding control sequences are "\n"
(for LF) and "\r\n"
for (CRLF).
Many versioning systems (like git and subversion) can automatically ensure the correct ending. However to cover all contingencies, you can activate this rule.
Rule Details
This rule enforces consistent line endings independent of operating system, VCS, or editor used across your codebase.
Options
This rule has a string option:
-
"unix"
(default) enforces the usage of Unix line endings:\n
for LF. -
"windows"
enforces the usage of Windows line endings:\r\n
for CRLF.
unix
Examples of incorrect code for this rule with the default "unix"
option:
/*eslint linebreak-style: ["error", "unix"]*/
var a = 'a'; // \r\n
Examples of correct code for this rule with the default "unix"
option:
/*eslint linebreak-style: ["error", "unix"]*/
var a = 'a', // \n
b = 'b'; // \n
// \n
function foo(params) { // \n
// do stuff \n
}// \n
windows
Examples of incorrect code for this rule with the "windows"
option:
/*eslint linebreak-style: ["error", "windows"]*/
var a = 'a'; // \n
Examples of correct code for this rule with the "windows"
option:
/*eslint linebreak-style: ["error", "windows"]*/
var a = 'a', // \r\n
b = 'b'; // \r\n
// \r\n
function foo(params) { // \r\n
// do stuff \r\n
} // \r\n
Using this rule with version control systems
Version control systems sometimes have special behavior for linebreaks. To make it easy for developers to contribute to your codebase from different platforms, you may want to configure your VCS to handle linebreaks appropriately.
For example, the default behavior of git on Windows systems is to convert LF linebreaks to CRLF when checking out files, but to store the linebreaks as LF when committing a change. This will cause the linebreak-style
rule to report errors if configured with the "unix"
setting, because the files that ESLint sees will have CRLF linebreaks. If you use git, you may want to add a line to your .gitattributes
file to prevent git from converting linebreaks in .js
files:
*.js text eol=lf
When Not To Use It
If you aren't concerned about having different line endings within your code, then you can safely turn this rule off.
Compatibility
- JSCS: validateLineBreaks Source: http://eslint.org/docs/rules/
Expected linebreaks to be 'LF' but found 'CRLF'. Open
/**
- Read upRead up
- Exclude checks
enforce consistent linebreak style (linebreak-style)
When developing with a lot of people all having different editors, VCS applications and operating systems it may occur that different line endings are written by either of the mentioned (might especially happen when using the windows and mac versions of SourceTree together).
The linebreaks (new lines) used in windows operating system are usually carriage returns (CR) followed by a line feed (LF) making it a carriage return line feed (CRLF)
whereas Linux and Unix use a simple line feed (LF). The corresponding control sequences are "\n"
(for LF) and "\r\n"
for (CRLF).
Many versioning systems (like git and subversion) can automatically ensure the correct ending. However to cover all contingencies, you can activate this rule.
Rule Details
This rule enforces consistent line endings independent of operating system, VCS, or editor used across your codebase.
Options
This rule has a string option:
-
"unix"
(default) enforces the usage of Unix line endings:\n
for LF. -
"windows"
enforces the usage of Windows line endings:\r\n
for CRLF.
unix
Examples of incorrect code for this rule with the default "unix"
option:
/*eslint linebreak-style: ["error", "unix"]*/
var a = 'a'; // \r\n
Examples of correct code for this rule with the default "unix"
option:
/*eslint linebreak-style: ["error", "unix"]*/
var a = 'a', // \n
b = 'b'; // \n
// \n
function foo(params) { // \n
// do stuff \n
}// \n
windows
Examples of incorrect code for this rule with the "windows"
option:
/*eslint linebreak-style: ["error", "windows"]*/
var a = 'a'; // \n
Examples of correct code for this rule with the "windows"
option:
/*eslint linebreak-style: ["error", "windows"]*/
var a = 'a', // \r\n
b = 'b'; // \r\n
// \r\n
function foo(params) { // \r\n
// do stuff \r\n
} // \r\n
Using this rule with version control systems
Version control systems sometimes have special behavior for linebreaks. To make it easy for developers to contribute to your codebase from different platforms, you may want to configure your VCS to handle linebreaks appropriately.
For example, the default behavior of git on Windows systems is to convert LF linebreaks to CRLF when checking out files, but to store the linebreaks as LF when committing a change. This will cause the linebreak-style
rule to report errors if configured with the "unix"
setting, because the files that ESLint sees will have CRLF linebreaks. If you use git, you may want to add a line to your .gitattributes
file to prevent git from converting linebreaks in .js
files:
*.js text eol=lf
When Not To Use It
If you aren't concerned about having different line endings within your code, then you can safely turn this rule off.
Compatibility
- JSCS: validateLineBreaks Source: http://eslint.org/docs/rules/
Expected property shorthand. Open
return $.notify({ title: title, message: message, onLast: onLast, sound: false })
- Read upRead up
- Exclude checks
Require Object Literal Shorthand Syntax (object-shorthand)
EcmaScript 6 provides a concise form for defining object literal methods and properties. This syntax can make defining complex object literals much cleaner.
Here are a few common examples using the ES5 syntax:
// properties
var foo = {
x: x,
y: y,
z: z,
};
// methods
var foo = {
a: function() {},
b: function() {}
};
Now here are ES6 equivalents:
/*eslint-env es6*/
// properties
var foo = {x, y, z};
// methods
var foo = {
a() {},
b() {}
};
Rule Details
This rule enforces the use of the shorthand syntax. This applies to all methods (including generators) defined in object literals and any properties defined where the key name matches name of the assigned variable.
Each of the following properties would warn:
/*eslint object-shorthand: "error"*/
/*eslint-env es6*/
var foo = {
w: function() {},
x: function *() {},
[y]: function() {},
z: z
};
In that case the expected syntax would have been:
/*eslint object-shorthand: "error"*/
/*eslint-env es6*/
var foo = {
w() {},
*x() {},
[y]() {},
z
};
This rule does not flag arrow functions inside of object literals. The following will not warn:
/*eslint object-shorthand: "error"*/
/*eslint-env es6*/
var foo = {
x: (y) => y
};
Options
The rule takes an option which specifies when it should be applied. It can be set to one of the following values:
-
"always"
(default) expects that the shorthand will be used whenever possible. -
"methods"
ensures the method shorthand is used (also applies to generators). -
"properties"
ensures the property shorthand is used (where the key and variable name match). -
"never"
ensures that no property or method shorthand is used in any object literal. -
"consistent"
ensures that either all shorthand or all longform will be used in an object literal. -
"consistent-as-needed"
ensures that either all shorthand or all longform will be used in an object literal, but ensures all shorthand whenever possible.
You can set the option in configuration like this:
{
"object-shorthand": ["error", "always"]
}
Additionally, the rule takes an optional object configuration:
-
"avoidQuotes": true
indicates that longform syntax is preferred whenever the object key is a string literal (default:false
). Note that this option can only be enabled when the string option is set to"always"
,"methods"
, or"properties"
. -
"ignoreConstructors": true
can be used to prevent the rule from reporting errors for constructor functions. (By default, the rule treats constructors the same way as other functions.) Note that this option can only be enabled when the string option is set to"always"
or"methods"
. -
"avoidExplicitReturnArrows": true
indicates that methods are preferred over explicit-return arrow functions for function properties. (By default, the rule allows either of these.) Note that this option can only be enabled when the string option is set to"always"
or"methods"
.
avoidQuotes
{
"object-shorthand": ["error", "always", { "avoidQuotes": true }]
}
Example of incorrect code for this rule with the "always", { "avoidQuotes": true }
option:
/*eslint object-shorthand: ["error", "always", { "avoidQuotes": true }]*/
/*eslint-env es6*/
var foo = {
"bar-baz"() {}
};
Example of correct code for this rule with the "always", { "avoidQuotes": true }
option:
/*eslint object-shorthand: ["error", "always", { "avoidQuotes": true }]*/
/*eslint-env es6*/
var foo = {
"bar-baz": function() {},
"qux": qux
};
ignoreConstructors
{
"object-shorthand": ["error", "always", { "ignoreConstructors": true }]
}
Example of correct code for this rule with the "always", { "ignoreConstructors": true }
option:
/*eslint object-shorthand: ["error", "always", { "ignoreConstructors": true }]*/
/*eslint-env es6*/
var foo = {
ConstructorFunction: function() {}
};
avoidExplicitReturnArrows
{
"object-shorthand": ["error", "always", { "avoidExplicitReturnArrows": true }]
}
Example of incorrect code for this rule with the "always", { "avoidExplicitReturnArrows": true }
option:
/*eslint object-shorthand: ["error", "always", { "avoidExplicitReturnArrows": true }]*/
/*eslint-env es6*/
var foo = {
foo: (bar, baz) => {
return bar + baz;
},
qux: (foobar) => {
return foobar * 2;
}
};
Example of correct code for this rule with the "always", { "avoidExplicitReturnArrows": true }
option:
/*eslint object-shorthand: ["error", "always", { "avoidExplicitReturnArrows": true }]*/
/*eslint-env es6*/
var foo = {
foo(bar, baz) {
return bar + baz;
},
qux: foobar => foobar * 2
};
Example of incorrect code for this rule with the "consistent"
option:
/*eslint object-shorthand: [2, "consistent"]*/
/*eslint-env es6*/
var foo = {
a,
b: "foo",
};
Examples of correct code for this rule with the "consistent"
option:
/*eslint object-shorthand: [2, "consistent"]*/
/*eslint-env es6*/
var foo = {
a: a,
b: "foo"
};
var bar = {
a,
b,
};
Example of incorrect code with the "consistent-as-needed"
option, which is very similar to "consistent"
:
/*eslint object-shorthand: [2, "consistent-as-needed"]*/
/*eslint-env es6*/
var foo = {
a: a,
b: b,
};
When Not To Use It
Anyone not yet in an ES6 environment would not want to apply this rule. Others may find the terseness of the shorthand syntax harder to read and may not want to encourage it with this rule.
Further Reading
Object initializer - MDN Source: http://eslint.org/docs/rules/