Showing 111 of 111 total issues
Closing curly brace does not appear on the same line as the subsequent block. Open
else {
- Read upRead up
- Exclude checks
Require Brace Style (brace-style)
Brace style is closely related to indent style in programming and describes the placement of braces relative to their control statement and body. There are probably a dozen, if not more, brace styles in the world.
The one true brace style is one of the most common brace styles in JavaScript, in which the opening brace of a block is placed on the same line as its corresponding statement or declaration. For example:
if (foo) {
bar();
} else {
baz();
}
One common variant of one true brace style is called Stroustrup, in which the else
statements in an if-else
construct, as well as catch
and finally
, must be on its own line after the preceding closing brace. For example:
if (foo) {
bar();
}
else {
baz();
}
Another style is called Allman, in which all the braces are expected to be on their own lines without any extra indentation. For example:
if (foo)
{
bar();
}
else
{
baz();
}
While no style is considered better than the other, most developers agree that having a consistent style throughout a project is important for its long-term maintainability.
Rule Details
This rule enforces consistent brace style for blocks.
Options
This rule has a string option:
-
"1tbs"
(default) enforces one true brace style -
"stroustrup"
enforces Stroustrup style -
"allman"
enforces Allman style
This rule has an object option for an exception:
-
"allowSingleLine": true
(defaultfalse
) allows the opening and closing braces for a block to be on the same line
1tbs
Examples of incorrect code for this rule with the default "1tbs"
option:
/*eslint brace-style: "error"*/
function foo()
{
return true;
}
if (foo)
{
bar();
}
try
{
somethingRisky();
} catch(e)
{
handleError();
}
if (foo) {
bar();
}
else {
baz();
}
Examples of correct code for this rule with the default "1tbs"
option:
/*eslint brace-style: "error"*/
function foo() {
return true;
}
if (foo) {
bar();
}
if (foo) {
bar();
} else {
baz();
}
try {
somethingRisky();
} catch(e) {
handleError();
}
// when there are no braces, there are no problems
if (foo) bar();
else if (baz) boom();
Examples of correct code for this rule with the "1tbs", { "allowSingleLine": true }
options:
/*eslint brace-style: ["error", "1tbs", { "allowSingleLine": true }]*/
function nop() { return; }
if (foo) { bar(); }
if (foo) { bar(); } else { baz(); }
try { somethingRisky(); } catch(e) { handleError(); }
stroustrup
Examples of incorrect code for this rule with the "stroustrup"
option:
/*eslint brace-style: ["error", "stroustrup"]*/
function foo()
{
return true;
}
if (foo)
{
bar();
}
try
{
somethingRisky();
} catch(e)
{
handleError();
}
if (foo) {
bar();
} else {
baz();
}
Examples of correct code for this rule with the "stroustrup"
option:
/*eslint brace-style: ["error", "stroustrup"]*/
function foo() {
return true;
}
if (foo) {
bar();
}
if (foo) {
bar();
}
else {
baz();
}
try {
somethingRisky();
}
catch(e) {
handleError();
}
// when there are no braces, there are no problems
if (foo) bar();
else if (baz) boom();
Examples of correct code for this rule with the "stroustrup", { "allowSingleLine": true }
options:
/*eslint brace-style: ["error", "stroustrup", { "allowSingleLine": true }]*/
function nop() { return; }
if (foo) { bar(); }
if (foo) { bar(); }
else { baz(); }
try { somethingRisky(); }
catch(e) { handleError(); }
allman
Examples of incorrect code for this rule with the "allman"
option:
/*eslint brace-style: ["error", "allman"]*/
function foo() {
return true;
}
if (foo)
{
bar(); }
try
{
somethingRisky();
} catch(e)
{
handleError();
}
if (foo) {
bar();
} else {
baz();
}
Examples of correct code for this rule with the "allman"
option:
/*eslint brace-style: ["error", "allman"]*/
function foo()
{
return true;
}
if (foo)
{
bar();
}
if (foo)
{
bar();
}
else
{
baz();
}
try
{
somethingRisky();
}
catch(e)
{
handleError();
}
// when there are no braces, there are no problems
if (foo) bar();
else if (baz) boom();
Examples of correct code for this rule with the "allman", { "allowSingleLine": true }
options:
/*eslint brace-style: ["error", "allman", { "allowSingleLine": true }]*/
function nop() { return; }
if (foo) { bar(); }
if (foo) { bar(); }
else { baz(); }
try { somethingRisky(); }
catch(e) { handleError(); }
When Not To Use It
If your project will not be using the one true brace style, turn this rule off.
Further Reading
Expected '===' and instead saw '=='. Open
if (email == 'admin@gmail.com' && password == 'angular2') {
- Read upRead up
- Exclude checks
Require === and !== (eqeqeq)
It is considered good practice to use the type-safe equality operators ===
and !==
instead of their regular counterparts ==
and !=
.
The reason for this is that ==
and !=
do type coercion which follows the rather obscure Abstract Equality Comparison Algorithm.
For instance, the following statements are all considered true
:
[] == false
[] == ![]
3 == "03"
If one of those occurs in an innocent-looking statement such as a == b
the actual problem is very difficult to spot.
Rule Details
This rule is aimed at eliminating the type-unsafe equality operators.
Examples of incorrect code for this rule:
/*eslint eqeqeq: "error"*/
if (x == 42) { }
if ("" == text) { }
if (obj.getStuff() != undefined) { }
Options
smart
The "smart"
option enforces the use of ===
and !==
except for these cases:
- Comparing two literal values
- Evaluating the value of
typeof
- Comparing against
null
Examples of incorrect code for the "smart"
option:
/*eslint eqeqeq: ["error", "smart"]*/
// comparing two variables requires ===
a == b
// only one side is a literal
foo == true
bananas != 1
// comparing to undefined requires ===
value == undefined
Examples of correct code for the "smart"
option:
/*eslint eqeqeq: ["error", "smart"]*/
typeof foo == 'undefined'
'hello' != 'world'
0 == 0
true == true
foo == null
allow-null
The "allow-null"
option will enforce ===
and !==
in your code with one exception - it permits comparing to null
to check for null
or undefined
in a single expression.
Examples of incorrect code for the "allow-null"
option:
/*eslint eqeqeq: ["error", "allow-null"]*/
bananas != 1
typeof foo == 'undefined'
'hello' != 'world'
0 == 0
foo == undefined
Examples of correct code for the "allow-null"
option:
/*eslint eqeqeq: ["error", "allow-null"]*/
foo == null
When Not To Use It
If you don't want to enforce a style for using equality operators, then it's safe to disable this rule. Source: http://eslint.org/docs/rules/
'use strict' is unnecessary inside of modules. Open
'use strict';
- Read upRead up
- Exclude checks
Strict Mode Directives (strict)
A strict mode directive at the beginning of a script or function body enables strict mode semantics.
When used globally, the entire script, including all contained functions, are strict mode code:
"use strict";
It is also possible to specify function-level strict mode, such that strict mode applies only to the function in which the directive occurs:
function foo() {
"use strict";
return;
}
var bar = function() {
"use strict";
return;
};
Unlike scripts, ECMAScript modules are always in strict mode. Strict mode directives in ECMAScript modules have no effect.
Rule Details
This rule is aimed at using strict mode directives effectively, and as such, will flag any unexpected uses or omissions of strict mode directives.
Options
There are four options for this rule:
-
"safe"
- require"use strict"
globally when inside a module wrapper and in function scopes everywhere else. This is the default. -
"never"
- disallow"use strict"
. -
"global"
- require"use strict"
in the global scope. -
"function"
- require"use strict"
in function scopes only.
All strict mode directives are flagged as unnecessary if ECMAScript modules or implied strict mode are enabled (see [Specifying Parser Options](../user-guide/configuring#specifying-parser-options)). This behaviour does not depend on the rule options, but can be silenced by disabling this rule.
safe
Node.js and the CommonJS module system wrap modules inside a hidden function wrapper that defines each module's scope. The wrapper makes it safe to concatenate strict mode modules while maintaining their original strict mode directives. When the node
or commonjs
environments are enabled or globalReturn
is enabled in ecmaFeatures
, ESLint considers code to be inside the module wrapper, and "safe"
mode corresponds to "global"
mode and enforces global strict mode directives. Everywhere else, "safe"
mode corresponds to "function"
mode and enforces strict mode directives inside top-level functions.
never
This mode forbids any occurrence of a strict mode directive.
Examples of incorrect code for the "never"
option:
/*eslint strict: ["error", "never"]*/
"use strict";
function foo() {
"use strict";
return;
}
var bar = function() {
"use strict";
return;
};
foo();
bar();
Examples of correct code for the "never"
option:
/*eslint strict: ["error", "never"]*/
function foo() {
return;
}
var bar = function() {
return;
};
foo();
bar();
global
This mode ensures that all code is in strict mode and that there are no extraneous strict mode directives at the top level or in nested functions, which are themselves already strict by virtue of being contained in strict global code. It requires that global code contains exactly one strict mode directive. Strict mode directives inside functions are considered unnecessary. Multiple strict mode directives at any level also trigger warnings.
Examples of incorrect code for the "global"
option:
/*eslint strict: ["error", "global"]*/
"use strict";
"use strict";
function foo() {
"use strict";
return function() {
"use strict";
"use strict";
return;
};
}
foo();
Examples of correct code for the "global"
option:
/*eslint strict: ["error", "global"]*/
"use strict";
function foo() {
return function() {
return;
};
}
foo();
function
This mode ensures that all function bodies are strict mode code, while global code is not. Particularly if a build step concatenates multiple scripts, a strict mode directive in global code of one script could unintentionally enable strict mode in another script that was not intended to be strict code. It forbids any occurrence of a strict mode directive in global code. It requires exactly one strict mode directive in each function declaration or expression whose parent is global code. Strict mode directives inside nested functions are considered unnecessary. Multiple strict mode directives at any level also trigger warnings.
Examples of incorrect code for the "function"
option:
/*eslint strict: ["error", "function"]*/
"use strict";
function foo() {
// Missing strict mode directive
return function() {
"use strict"; // Unnecessary; parent should contain a strict mode directive
"use strict";
return;
};
}
foo();
Examples of correct code for the "function"
option:
/*eslint strict: ["error", "function"]*/
function foo() {
"use strict";
return function() {
return;
};
}
(function() {
"use strict";
return;
}());
foo();
earlier default (removed)
Replacement notice: This mode, previously enabled by turning on the rule without specifying a mode, has been removed in ESLint v1.0. "function"
mode is most similar to the deprecated behavior.
This mode ensures that all functions are executed in strict mode. A strict mode directive must be present in global code or in every top-level function declaration or expression. It does not concern itself with unnecessary strict mode directives in nested functions that are already strict, nor with multiple strict mode directives at the same level.
Examples of incorrect code for an earlier default option which has been removed:
// "strict": "error"
function foo() {
return true;
}
Examples of correct code for an earlier default option which has been removed:
// "strict": "error"
"use strict";
function foo() {
return true;
}
// "strict": "error"
function foo() {
"use strict";
return true;
}
// "strict": "error"
(function() {
"use strict";
// other code
}());
When Not To Use It
In a codebase that has both strict and non-strict code, either turn this rule off, or selectively disable it where necessary. For example, functions referencing arguments.callee
are invalid in strict mode. A full list of strict mode differences is available on MDN.
Source: http://eslint.org/docs/rules/
'use strict' is unnecessary inside of modules. Open
'use strict';
- Read upRead up
- Exclude checks
Strict Mode Directives (strict)
A strict mode directive at the beginning of a script or function body enables strict mode semantics.
When used globally, the entire script, including all contained functions, are strict mode code:
"use strict";
It is also possible to specify function-level strict mode, such that strict mode applies only to the function in which the directive occurs:
function foo() {
"use strict";
return;
}
var bar = function() {
"use strict";
return;
};
Unlike scripts, ECMAScript modules are always in strict mode. Strict mode directives in ECMAScript modules have no effect.
Rule Details
This rule is aimed at using strict mode directives effectively, and as such, will flag any unexpected uses or omissions of strict mode directives.
Options
There are four options for this rule:
-
"safe"
- require"use strict"
globally when inside a module wrapper and in function scopes everywhere else. This is the default. -
"never"
- disallow"use strict"
. -
"global"
- require"use strict"
in the global scope. -
"function"
- require"use strict"
in function scopes only.
All strict mode directives are flagged as unnecessary if ECMAScript modules or implied strict mode are enabled (see [Specifying Parser Options](../user-guide/configuring#specifying-parser-options)). This behaviour does not depend on the rule options, but can be silenced by disabling this rule.
safe
Node.js and the CommonJS module system wrap modules inside a hidden function wrapper that defines each module's scope. The wrapper makes it safe to concatenate strict mode modules while maintaining their original strict mode directives. When the node
or commonjs
environments are enabled or globalReturn
is enabled in ecmaFeatures
, ESLint considers code to be inside the module wrapper, and "safe"
mode corresponds to "global"
mode and enforces global strict mode directives. Everywhere else, "safe"
mode corresponds to "function"
mode and enforces strict mode directives inside top-level functions.
never
This mode forbids any occurrence of a strict mode directive.
Examples of incorrect code for the "never"
option:
/*eslint strict: ["error", "never"]*/
"use strict";
function foo() {
"use strict";
return;
}
var bar = function() {
"use strict";
return;
};
foo();
bar();
Examples of correct code for the "never"
option:
/*eslint strict: ["error", "never"]*/
function foo() {
return;
}
var bar = function() {
return;
};
foo();
bar();
global
This mode ensures that all code is in strict mode and that there are no extraneous strict mode directives at the top level or in nested functions, which are themselves already strict by virtue of being contained in strict global code. It requires that global code contains exactly one strict mode directive. Strict mode directives inside functions are considered unnecessary. Multiple strict mode directives at any level also trigger warnings.
Examples of incorrect code for the "global"
option:
/*eslint strict: ["error", "global"]*/
"use strict";
"use strict";
function foo() {
"use strict";
return function() {
"use strict";
"use strict";
return;
};
}
foo();
Examples of correct code for the "global"
option:
/*eslint strict: ["error", "global"]*/
"use strict";
function foo() {
return function() {
return;
};
}
foo();
function
This mode ensures that all function bodies are strict mode code, while global code is not. Particularly if a build step concatenates multiple scripts, a strict mode directive in global code of one script could unintentionally enable strict mode in another script that was not intended to be strict code. It forbids any occurrence of a strict mode directive in global code. It requires exactly one strict mode directive in each function declaration or expression whose parent is global code. Strict mode directives inside nested functions are considered unnecessary. Multiple strict mode directives at any level also trigger warnings.
Examples of incorrect code for the "function"
option:
/*eslint strict: ["error", "function"]*/
"use strict";
function foo() {
// Missing strict mode directive
return function() {
"use strict"; // Unnecessary; parent should contain a strict mode directive
"use strict";
return;
};
}
foo();
Examples of correct code for the "function"
option:
/*eslint strict: ["error", "function"]*/
function foo() {
"use strict";
return function() {
return;
};
}
(function() {
"use strict";
return;
}());
foo();
earlier default (removed)
Replacement notice: This mode, previously enabled by turning on the rule without specifying a mode, has been removed in ESLint v1.0. "function"
mode is most similar to the deprecated behavior.
This mode ensures that all functions are executed in strict mode. A strict mode directive must be present in global code or in every top-level function declaration or expression. It does not concern itself with unnecessary strict mode directives in nested functions that are already strict, nor with multiple strict mode directives at the same level.
Examples of incorrect code for an earlier default option which has been removed:
// "strict": "error"
function foo() {
return true;
}
Examples of correct code for an earlier default option which has been removed:
// "strict": "error"
"use strict";
function foo() {
return true;
}
// "strict": "error"
function foo() {
"use strict";
return true;
}
// "strict": "error"
(function() {
"use strict";
// other code
}());
When Not To Use It
In a codebase that has both strict and non-strict code, either turn this rule off, or selectively disable it where necessary. For example, functions referencing arguments.callee
are invalid in strict mode. A full list of strict mode differences is available on MDN.
Source: http://eslint.org/docs/rules/
'module' is not defined. Open
module.exports = {
- Read upRead up
- Exclude checks
Disallow Undeclared Variables (no-undef)
This rule can help you locate potential ReferenceErrors resulting from misspellings of variable and parameter names, or accidental implicit globals (for example, from forgetting the var
keyword in a for
loop initializer).
Rule Details
Any reference to an undeclared variable causes a warning, unless the variable is explicitly mentioned in a /*global ...*/
comment.
Examples of incorrect code for this rule:
/*eslint no-undef: "error"*/
var a = someFunction();
b = 10;
Examples of correct code for this rule with global
declaration:
/*global someFunction b:true*/
/*eslint no-undef: "error"*/
var a = someFunction();
b = 10;
The b:true
syntax in /*global */
indicates that assignment to b
is correct.
Examples of incorrect code for this rule with global
declaration:
/*global b*/
/*eslint no-undef: "error"*/
b = 10;
By default, variables declared in /*global */
are read-only, therefore assignment is incorrect.
Options
-
typeof
set to true will warn for variables used inside typeof check (Default false).
typeof
Examples of correct code for the default { "typeof": false }
option:
/*eslint no-undef: "error"*/
if (typeof UndefinedIdentifier === "undefined") {
// do something ...
}
You can use this option if you want to prevent typeof
check on a variable which has not been declared.
Examples of incorrect code for the { "typeof": true }
option:
/*eslint no-undef: ["error", { "typeof": true }] */
if(typeof a === "string"){}
Examples of correct code for the { "typeof": true }
option with global
declaration:
/*global a*/
/*eslint no-undef: ["error", { "typeof": true }] */
if(typeof a === "string"){}
Environments
For convenience, ESLint provides shortcuts that pre-define global variables exposed by popular libraries and runtime environments. This rule supports these environments, as listed in Specifying Environments. A few examples are given below.
browser
Examples of correct code for this rule with browser
environment:
/*eslint no-undef: "error"*/
/*eslint-env browser*/
setTimeout(function() {
alert("Hello");
});
node
Examples of correct code for this rule with node
environment:
/*eslint no-undef: "error"*/
/*eslint-env node*/
var fs = require("fs");
module.exports = function() {
console.log(fs);
};
When Not To Use It
If explicit declaration of global variables is not to your taste.
Compatibility
This rule provides compatibility with treatment of global variables in JSHint and JSLint.
Further Reading
Missing semicolon. Open
}
- Read upRead up
- Exclude checks
Enforce or Disallow Semicolons (semi)
(fixable) The --fix
option on the [command line](../user-guide/command-line-interface#fix) automatically fixes problems reported by this rule.
JavaScript is unique amongst the C-like languages in that it doesn't require semicolons at the end of each statement. In many cases, the JavaScript engine can determine that a semicolon should be in a certain spot and will automatically add it. This feature is known as automatic semicolon insertion (ASI) and is considered one of the more controversial features of JavaScript. For example, the following lines are both valid:
var name = "ESLint"
var website = "eslint.org";
On the first line, the JavaScript engine will automatically insert a semicolon, so this is not considered a syntax error. The JavaScript engine still knows how to interpret the line and knows that the line end indicates the end of the statement.
In the debate over ASI, there are generally two schools of thought. The first is that we should treat ASI as if it didn't exist and always include semicolons manually. The rationale is that it's easier to always include semicolons than to try to remember when they are or are not required, and thus decreases the possibility of introducing an error.
However, the ASI mechanism can sometimes be tricky to people who are using semicolons. For example, consider this code:
return
{
name: "ESLint"
};
This may look like a return
statement that returns an object literal, however, the JavaScript engine will interpret this code as:
return;
{
name: "ESLint";
}
Effectively, a semicolon is inserted after the return
statement, causing the code below it (a labeled literal inside a block) to be unreachable. This rule and the [no-unreachable](no-unreachable.md) rule will protect your code from such cases.
On the other side of the argument are those who says that since semicolons are inserted automatically, they are optional and do not need to be inserted manually. However, the ASI mechanism can also be tricky to people who don't use semicolons. For example, consider this code:
var globalCounter = { }
(function () {
var n = 0
globalCounter.increment = function () {
return ++n
}
})()
In this example, a semicolon will not be inserted after the first line, causing a run-time error (because an empty object is called as if it's a function). The [no-unexpected-multiline](no-unexpected-multiline.md) rule can protect your code from such cases.
Although ASI allows for more freedom over your coding style, it can also make your code behave in an unexpected way, whether you use semicolons or not. Therefore, it is best to know when ASI takes place and when it does not, and have ESLint protect your code from these potentially unexpected cases. In short, as once described by Isaac Schlueter, a \n
character always ends a statement (just like a semicolon) unless one of the following is true:
- The statement has an unclosed paren, array literal, or object literal or ends in some other way that is not a valid way to end a statement. (For instance, ending with
.
or,
.) - The line is
--
or++
(in which case it will decrement/increment the next token.) - It is a
for()
,while()
,do
,if()
, orelse
, and there is no{
- The next line starts with
[
,(
,+
,*
,/
,-
,,
,.
, or some other binary operator that can only be found between two tokens in a single expression.
Rule Details
This rule is aimed at ensuring consistent use of semicolons. You can decide whether or not to require semicolons at the end of statements.
Options
The rule takes one or two options. The first one is a string, which could be "always"
or "never"
. The default is "always"
. The second one is an object for more fine-grained configuration when the first option is "always"
.
You can set the option in configuration like this:
"always"
By using the default option, semicolons must be used any place where they are valid.
semi: ["error", "always"]
The following patterns are considered problems:
/*eslint semi: "error"*/
var name = "ESLint"
object.method = function() {
// ...
}
The following patterns are not considered problems:
/*eslint semi: "error"*/
var name = "ESLint";
object.method = function() {
// ...
};
Fine-grained control
When setting the first option as "always", an additional option can be added to omit the last semicolon in a one-line block, that is, a block in which its braces (and therefore the content of the block) are in the same line:
semi: ["error", "always", { "omitLastInOneLineBlock": true}]
The following patterns are considered problems:
/*eslint semi: ["error", "always", { "omitLastInOneLineBlock": true}] */
if (foo) {
bar()
}
if (foo) { bar(); }
The following patterns are not considered problems:
/*eslint semi: ["error", "always", { "omitLastInOneLineBlock": true}] */
if (foo) { bar() }
if (foo) { bar(); baz() }
"never"
If you want to enforce that semicolons are never used, switch the configuration to:
semi: [2, "never"]
Then, the following patterns are considered problems:
/*eslint semi: ["error", "never"]*/
var name = "ESLint";
object.method = function() {
// ...
};
And the following patterns are not considered problems:
/*eslint semi: ["error", "never"]*/
var name = "ESLint"
object.method = function() {
// ...
}
Even in "never"
mode, semicolons are still allowed to disambiguate statements beginning with [
, (
, /
, +
, or -
:
/*eslint semi: ["error", "never"]*/
var name = "ESLint"
;(function() {
// ...
})()
When Not To Use It
If you do not want to enforce semicolon usage (or omission) in any particular way, then you can turn this rule off.
Further Reading
- An Open Letter to JavaScript Leaders Regarding Semicolons
- JavaScript Semicolon Insertion
- Understanding Automatic Semicolon Insertion in JavaScript
Related Rules
- [no-extra-semi](no-extra-semi.md)
- [no-unexpected-multiline](no-unexpected-multiline.md)
- [semi-spacing](semi-spacing.md) Source: http://eslint.org/docs/rules/
A space is required before '}' Open
this.body = {success: true};
- Read upRead up
- Exclude checks
Disallow or enforce spaces inside of curly braces in objects. (object-curly-spacing)
(fixable) The --fix
option on the [command line](../user-guide/command-line-interface#fix) automatically fixes problems reported by this rule.
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 aims to maintain consistency around the spacing inside of object literals. It also applies to EcmaScript 6 destructured assignment and import/export specifiers.
It either requires or disallows spaces between those braces and the values inside of them. Braces that are separated from the adjacent value by a new line are exempt from this rule.
Options
There are two main options for the rule:
-
"always"
enforces a space inside of curly braces -
"never"
disallows spaces inside of curly braces (default)
Depending on your coding conventions, you can choose either option by specifying it in your configuration:
"object-curly-spacing": ["error", "always"]
"never"
When "never"
is set, the following patterns are considered problems:
/*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';
The following patterns are not considered problems:
/*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"
When "always"
is used, the following patterns are considered problems:
/*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';
The following patterns are not considered problems:
/*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';
Note that {}
is always exempt from spacing requirements with this rule.
Exceptions
There are two exceptions you can apply to this rule: objectsInObjects
and
arraysInObjects
. Their values can be set to either true
or false
as part
of an object literal set as the 3rd argument for the rule.
These exceptions work in the context of the first option.
That is, if "always"
is set to enforce spacing and an exception is set to false
,
it will disallow spacing for cases matching the exception. Likewise,
if "never"
is set to disallow spacing and an exception is set to true
,
it will enforce spacing for cases matching the exception.
You can add exceptions like so:
"object-curly-spacing": ["error", "always", {
"objectsInObjects": false,
"arraysInObjects": false
}]
objectsInObjects
In the case of the "always"
option, set objectsInObjects
exception to false
to
enforce the following syntax (notice the }}
at the end):
var obj = { "foo": { "baz": 1, "bar": 2 }};
In the case of the "never"
option, set objectsInObjects
exception to true
to enforce
the following style (with a space between the }
at the end:
var obj = {"foo": {"baz": 1, "bar": 2} };
arraysInObjects
In the case of the "always"
option, set arraysInObjects
exception to false
to
enforce the following syntax (notice the ]}
at the end):
var obj = { "foo": [ 1, 2 ]};
var obj = { "foo": [ "baz", "bar" ]};
In the case of the "never"
option, set arraysInObjects
exception to true
to enforce
the following style (with a space between the ]
and }
at the end:
var obj = {"foo": [ 1, 2 ] };
var obj = {"foo": [ "baz", "bar" ] };
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)
- [space-in-brackets](space-in-brackets.md) (deprecated) Source: http://eslint.org/docs/rules/
'use strict' is unnecessary inside of modules. Open
'use strict';
- Read upRead up
- Exclude checks
Strict Mode Directives (strict)
A strict mode directive at the beginning of a script or function body enables strict mode semantics.
When used globally, the entire script, including all contained functions, are strict mode code:
"use strict";
It is also possible to specify function-level strict mode, such that strict mode applies only to the function in which the directive occurs:
function foo() {
"use strict";
return;
}
var bar = function() {
"use strict";
return;
};
Unlike scripts, ECMAScript modules are always in strict mode. Strict mode directives in ECMAScript modules have no effect.
Rule Details
This rule is aimed at using strict mode directives effectively, and as such, will flag any unexpected uses or omissions of strict mode directives.
Options
There are four options for this rule:
-
"safe"
- require"use strict"
globally when inside a module wrapper and in function scopes everywhere else. This is the default. -
"never"
- disallow"use strict"
. -
"global"
- require"use strict"
in the global scope. -
"function"
- require"use strict"
in function scopes only.
All strict mode directives are flagged as unnecessary if ECMAScript modules or implied strict mode are enabled (see [Specifying Parser Options](../user-guide/configuring#specifying-parser-options)). This behaviour does not depend on the rule options, but can be silenced by disabling this rule.
safe
Node.js and the CommonJS module system wrap modules inside a hidden function wrapper that defines each module's scope. The wrapper makes it safe to concatenate strict mode modules while maintaining their original strict mode directives. When the node
or commonjs
environments are enabled or globalReturn
is enabled in ecmaFeatures
, ESLint considers code to be inside the module wrapper, and "safe"
mode corresponds to "global"
mode and enforces global strict mode directives. Everywhere else, "safe"
mode corresponds to "function"
mode and enforces strict mode directives inside top-level functions.
never
This mode forbids any occurrence of a strict mode directive.
Examples of incorrect code for the "never"
option:
/*eslint strict: ["error", "never"]*/
"use strict";
function foo() {
"use strict";
return;
}
var bar = function() {
"use strict";
return;
};
foo();
bar();
Examples of correct code for the "never"
option:
/*eslint strict: ["error", "never"]*/
function foo() {
return;
}
var bar = function() {
return;
};
foo();
bar();
global
This mode ensures that all code is in strict mode and that there are no extraneous strict mode directives at the top level or in nested functions, which are themselves already strict by virtue of being contained in strict global code. It requires that global code contains exactly one strict mode directive. Strict mode directives inside functions are considered unnecessary. Multiple strict mode directives at any level also trigger warnings.
Examples of incorrect code for the "global"
option:
/*eslint strict: ["error", "global"]*/
"use strict";
"use strict";
function foo() {
"use strict";
return function() {
"use strict";
"use strict";
return;
};
}
foo();
Examples of correct code for the "global"
option:
/*eslint strict: ["error", "global"]*/
"use strict";
function foo() {
return function() {
return;
};
}
foo();
function
This mode ensures that all function bodies are strict mode code, while global code is not. Particularly if a build step concatenates multiple scripts, a strict mode directive in global code of one script could unintentionally enable strict mode in another script that was not intended to be strict code. It forbids any occurrence of a strict mode directive in global code. It requires exactly one strict mode directive in each function declaration or expression whose parent is global code. Strict mode directives inside nested functions are considered unnecessary. Multiple strict mode directives at any level also trigger warnings.
Examples of incorrect code for the "function"
option:
/*eslint strict: ["error", "function"]*/
"use strict";
function foo() {
// Missing strict mode directive
return function() {
"use strict"; // Unnecessary; parent should contain a strict mode directive
"use strict";
return;
};
}
foo();
Examples of correct code for the "function"
option:
/*eslint strict: ["error", "function"]*/
function foo() {
"use strict";
return function() {
return;
};
}
(function() {
"use strict";
return;
}());
foo();
earlier default (removed)
Replacement notice: This mode, previously enabled by turning on the rule without specifying a mode, has been removed in ESLint v1.0. "function"
mode is most similar to the deprecated behavior.
This mode ensures that all functions are executed in strict mode. A strict mode directive must be present in global code or in every top-level function declaration or expression. It does not concern itself with unnecessary strict mode directives in nested functions that are already strict, nor with multiple strict mode directives at the same level.
Examples of incorrect code for an earlier default option which has been removed:
// "strict": "error"
function foo() {
return true;
}
Examples of correct code for an earlier default option which has been removed:
// "strict": "error"
"use strict";
function foo() {
return true;
}
// "strict": "error"
function foo() {
"use strict";
return true;
}
// "strict": "error"
(function() {
"use strict";
// other code
}());
When Not To Use It
In a codebase that has both strict and non-strict code, either turn this rule off, or selectively disable it where necessary. For example, functions referencing arguments.callee
are invalid in strict mode. A full list of strict mode differences is available on MDN.
Source: http://eslint.org/docs/rules/
'use strict' is unnecessary inside of modules. Open
'use strict';
- Read upRead up
- Exclude checks
Strict Mode Directives (strict)
A strict mode directive at the beginning of a script or function body enables strict mode semantics.
When used globally, the entire script, including all contained functions, are strict mode code:
"use strict";
It is also possible to specify function-level strict mode, such that strict mode applies only to the function in which the directive occurs:
function foo() {
"use strict";
return;
}
var bar = function() {
"use strict";
return;
};
Unlike scripts, ECMAScript modules are always in strict mode. Strict mode directives in ECMAScript modules have no effect.
Rule Details
This rule is aimed at using strict mode directives effectively, and as such, will flag any unexpected uses or omissions of strict mode directives.
Options
There are four options for this rule:
-
"safe"
- require"use strict"
globally when inside a module wrapper and in function scopes everywhere else. This is the default. -
"never"
- disallow"use strict"
. -
"global"
- require"use strict"
in the global scope. -
"function"
- require"use strict"
in function scopes only.
All strict mode directives are flagged as unnecessary if ECMAScript modules or implied strict mode are enabled (see [Specifying Parser Options](../user-guide/configuring#specifying-parser-options)). This behaviour does not depend on the rule options, but can be silenced by disabling this rule.
safe
Node.js and the CommonJS module system wrap modules inside a hidden function wrapper that defines each module's scope. The wrapper makes it safe to concatenate strict mode modules while maintaining their original strict mode directives. When the node
or commonjs
environments are enabled or globalReturn
is enabled in ecmaFeatures
, ESLint considers code to be inside the module wrapper, and "safe"
mode corresponds to "global"
mode and enforces global strict mode directives. Everywhere else, "safe"
mode corresponds to "function"
mode and enforces strict mode directives inside top-level functions.
never
This mode forbids any occurrence of a strict mode directive.
Examples of incorrect code for the "never"
option:
/*eslint strict: ["error", "never"]*/
"use strict";
function foo() {
"use strict";
return;
}
var bar = function() {
"use strict";
return;
};
foo();
bar();
Examples of correct code for the "never"
option:
/*eslint strict: ["error", "never"]*/
function foo() {
return;
}
var bar = function() {
return;
};
foo();
bar();
global
This mode ensures that all code is in strict mode and that there are no extraneous strict mode directives at the top level or in nested functions, which are themselves already strict by virtue of being contained in strict global code. It requires that global code contains exactly one strict mode directive. Strict mode directives inside functions are considered unnecessary. Multiple strict mode directives at any level also trigger warnings.
Examples of incorrect code for the "global"
option:
/*eslint strict: ["error", "global"]*/
"use strict";
"use strict";
function foo() {
"use strict";
return function() {
"use strict";
"use strict";
return;
};
}
foo();
Examples of correct code for the "global"
option:
/*eslint strict: ["error", "global"]*/
"use strict";
function foo() {
return function() {
return;
};
}
foo();
function
This mode ensures that all function bodies are strict mode code, while global code is not. Particularly if a build step concatenates multiple scripts, a strict mode directive in global code of one script could unintentionally enable strict mode in another script that was not intended to be strict code. It forbids any occurrence of a strict mode directive in global code. It requires exactly one strict mode directive in each function declaration or expression whose parent is global code. Strict mode directives inside nested functions are considered unnecessary. Multiple strict mode directives at any level also trigger warnings.
Examples of incorrect code for the "function"
option:
/*eslint strict: ["error", "function"]*/
"use strict";
function foo() {
// Missing strict mode directive
return function() {
"use strict"; // Unnecessary; parent should contain a strict mode directive
"use strict";
return;
};
}
foo();
Examples of correct code for the "function"
option:
/*eslint strict: ["error", "function"]*/
function foo() {
"use strict";
return function() {
return;
};
}
(function() {
"use strict";
return;
}());
foo();
earlier default (removed)
Replacement notice: This mode, previously enabled by turning on the rule without specifying a mode, has been removed in ESLint v1.0. "function"
mode is most similar to the deprecated behavior.
This mode ensures that all functions are executed in strict mode. A strict mode directive must be present in global code or in every top-level function declaration or expression. It does not concern itself with unnecessary strict mode directives in nested functions that are already strict, nor with multiple strict mode directives at the same level.
Examples of incorrect code for an earlier default option which has been removed:
// "strict": "error"
function foo() {
return true;
}
Examples of correct code for an earlier default option which has been removed:
// "strict": "error"
"use strict";
function foo() {
return true;
}
// "strict": "error"
function foo() {
"use strict";
return true;
}
// "strict": "error"
(function() {
"use strict";
// other code
}());
When Not To Use It
In a codebase that has both strict and non-strict code, either turn this rule off, or selectively disable it where necessary. For example, functions referencing arguments.callee
are invalid in strict mode. A full list of strict mode differences is available on MDN.
Source: http://eslint.org/docs/rules/
Unexpected console statement. Open
console.log(`Listening on port ${config.port}`);
- Read upRead up
- Exclude checks
disallow the use of console
(no-console)
In JavaScript that is designed to be executed in the browser, it's considered a best practice to avoid using methods on console
. Such messages are considered to be for debugging purposes and therefore not suitable to ship to the client. In general, calls using console
should be stripped before being pushed to production.
console.log("Made it here.");
console.error("That shouldn't have happened.");
Rule Details
This rule disallows calls to methods of the console
object.
Examples of incorrect code for this rule:
/*eslint no-console: "error"*/
console.log("Log a debug level message.");
console.warn("Log a warn level message.");
console.error("Log an error level message.");
Examples of correct code for this rule:
/*eslint no-console: "error"*/
// custom console
Console.log("Hello world!");
Options
This rule has an object option for exceptions:
-
"allow"
has an array of strings which are allowed methods of theconsole
object
Examples of additional correct code for this rule with a sample { "allow": ["warn", "error"] }
option:
/*eslint no-console: ["error", { allow: ["warn", "error"] }] */
console.warn("Log a warn level message.");
console.error("Log an error level message.");
When Not To Use It
If you're using Node.js, however, console
is used to output information to the user and so is not strictly used for debugging purposes. If you are developing for Node.js then you most likely do not want this rule enabled.
Related Rules
- [no-alert](no-alert.md)
- [no-debugger](no-debugger.md) Source: http://eslint.org/docs/rules/
'module' is not defined. Open
module.exports = function() {
- Read upRead up
- Exclude checks
Disallow Undeclared Variables (no-undef)
This rule can help you locate potential ReferenceErrors resulting from misspellings of variable and parameter names, or accidental implicit globals (for example, from forgetting the var
keyword in a for
loop initializer).
Rule Details
Any reference to an undeclared variable causes a warning, unless the variable is explicitly mentioned in a /*global ...*/
comment.
Examples of incorrect code for this rule:
/*eslint no-undef: "error"*/
var a = someFunction();
b = 10;
Examples of correct code for this rule with global
declaration:
/*global someFunction b:true*/
/*eslint no-undef: "error"*/
var a = someFunction();
b = 10;
The b:true
syntax in /*global */
indicates that assignment to b
is correct.
Examples of incorrect code for this rule with global
declaration:
/*global b*/
/*eslint no-undef: "error"*/
b = 10;
By default, variables declared in /*global */
are read-only, therefore assignment is incorrect.
Options
-
typeof
set to true will warn for variables used inside typeof check (Default false).
typeof
Examples of correct code for the default { "typeof": false }
option:
/*eslint no-undef: "error"*/
if (typeof UndefinedIdentifier === "undefined") {
// do something ...
}
You can use this option if you want to prevent typeof
check on a variable which has not been declared.
Examples of incorrect code for the { "typeof": true }
option:
/*eslint no-undef: ["error", { "typeof": true }] */
if(typeof a === "string"){}
Examples of correct code for the { "typeof": true }
option with global
declaration:
/*global a*/
/*eslint no-undef: ["error", { "typeof": true }] */
if(typeof a === "string"){}
Environments
For convenience, ESLint provides shortcuts that pre-define global variables exposed by popular libraries and runtime environments. This rule supports these environments, as listed in Specifying Environments. A few examples are given below.
browser
Examples of correct code for this rule with browser
environment:
/*eslint no-undef: "error"*/
/*eslint-env browser*/
setTimeout(function() {
alert("Hello");
});
node
Examples of correct code for this rule with node
environment:
/*eslint no-undef: "error"*/
/*eslint-env node*/
var fs = require("fs");
module.exports = function() {
console.log(fs);
};
When Not To Use It
If explicit declaration of global variables is not to your taste.
Compatibility
This rule provides compatibility with treatment of global variables in JSHint and JSLint.
Further Reading
'module' is not defined. Open
module.exports = function() {
- Read upRead up
- Exclude checks
Disallow Undeclared Variables (no-undef)
This rule can help you locate potential ReferenceErrors resulting from misspellings of variable and parameter names, or accidental implicit globals (for example, from forgetting the var
keyword in a for
loop initializer).
Rule Details
Any reference to an undeclared variable causes a warning, unless the variable is explicitly mentioned in a /*global ...*/
comment.
Examples of incorrect code for this rule:
/*eslint no-undef: "error"*/
var a = someFunction();
b = 10;
Examples of correct code for this rule with global
declaration:
/*global someFunction b:true*/
/*eslint no-undef: "error"*/
var a = someFunction();
b = 10;
The b:true
syntax in /*global */
indicates that assignment to b
is correct.
Examples of incorrect code for this rule with global
declaration:
/*global b*/
/*eslint no-undef: "error"*/
b = 10;
By default, variables declared in /*global */
are read-only, therefore assignment is incorrect.
Options
-
typeof
set to true will warn for variables used inside typeof check (Default false).
typeof
Examples of correct code for the default { "typeof": false }
option:
/*eslint no-undef: "error"*/
if (typeof UndefinedIdentifier === "undefined") {
// do something ...
}
You can use this option if you want to prevent typeof
check on a variable which has not been declared.
Examples of incorrect code for the { "typeof": true }
option:
/*eslint no-undef: ["error", { "typeof": true }] */
if(typeof a === "string"){}
Examples of correct code for the { "typeof": true }
option with global
declaration:
/*global a*/
/*eslint no-undef: ["error", { "typeof": true }] */
if(typeof a === "string"){}
Environments
For convenience, ESLint provides shortcuts that pre-define global variables exposed by popular libraries and runtime environments. This rule supports these environments, as listed in Specifying Environments. A few examples are given below.
browser
Examples of correct code for this rule with browser
environment:
/*eslint no-undef: "error"*/
/*eslint-env browser*/
setTimeout(function() {
alert("Hello");
});
node
Examples of correct code for this rule with node
environment:
/*eslint no-undef: "error"*/
/*eslint-env node*/
var fs = require("fs");
module.exports = function() {
console.log(fs);
};
When Not To Use It
If explicit declaration of global variables is not to your taste.
Compatibility
This rule provides compatibility with treatment of global variables in JSHint and JSLint.
Further Reading
'use strict' is unnecessary inside of modules. Open
'use strict';
- Read upRead up
- Exclude checks
Strict Mode Directives (strict)
A strict mode directive at the beginning of a script or function body enables strict mode semantics.
When used globally, the entire script, including all contained functions, are strict mode code:
"use strict";
It is also possible to specify function-level strict mode, such that strict mode applies only to the function in which the directive occurs:
function foo() {
"use strict";
return;
}
var bar = function() {
"use strict";
return;
};
Unlike scripts, ECMAScript modules are always in strict mode. Strict mode directives in ECMAScript modules have no effect.
Rule Details
This rule is aimed at using strict mode directives effectively, and as such, will flag any unexpected uses or omissions of strict mode directives.
Options
There are four options for this rule:
-
"safe"
- require"use strict"
globally when inside a module wrapper and in function scopes everywhere else. This is the default. -
"never"
- disallow"use strict"
. -
"global"
- require"use strict"
in the global scope. -
"function"
- require"use strict"
in function scopes only.
All strict mode directives are flagged as unnecessary if ECMAScript modules or implied strict mode are enabled (see [Specifying Parser Options](../user-guide/configuring#specifying-parser-options)). This behaviour does not depend on the rule options, but can be silenced by disabling this rule.
safe
Node.js and the CommonJS module system wrap modules inside a hidden function wrapper that defines each module's scope. The wrapper makes it safe to concatenate strict mode modules while maintaining their original strict mode directives. When the node
or commonjs
environments are enabled or globalReturn
is enabled in ecmaFeatures
, ESLint considers code to be inside the module wrapper, and "safe"
mode corresponds to "global"
mode and enforces global strict mode directives. Everywhere else, "safe"
mode corresponds to "function"
mode and enforces strict mode directives inside top-level functions.
never
This mode forbids any occurrence of a strict mode directive.
Examples of incorrect code for the "never"
option:
/*eslint strict: ["error", "never"]*/
"use strict";
function foo() {
"use strict";
return;
}
var bar = function() {
"use strict";
return;
};
foo();
bar();
Examples of correct code for the "never"
option:
/*eslint strict: ["error", "never"]*/
function foo() {
return;
}
var bar = function() {
return;
};
foo();
bar();
global
This mode ensures that all code is in strict mode and that there are no extraneous strict mode directives at the top level or in nested functions, which are themselves already strict by virtue of being contained in strict global code. It requires that global code contains exactly one strict mode directive. Strict mode directives inside functions are considered unnecessary. Multiple strict mode directives at any level also trigger warnings.
Examples of incorrect code for the "global"
option:
/*eslint strict: ["error", "global"]*/
"use strict";
"use strict";
function foo() {
"use strict";
return function() {
"use strict";
"use strict";
return;
};
}
foo();
Examples of correct code for the "global"
option:
/*eslint strict: ["error", "global"]*/
"use strict";
function foo() {
return function() {
return;
};
}
foo();
function
This mode ensures that all function bodies are strict mode code, while global code is not. Particularly if a build step concatenates multiple scripts, a strict mode directive in global code of one script could unintentionally enable strict mode in another script that was not intended to be strict code. It forbids any occurrence of a strict mode directive in global code. It requires exactly one strict mode directive in each function declaration or expression whose parent is global code. Strict mode directives inside nested functions are considered unnecessary. Multiple strict mode directives at any level also trigger warnings.
Examples of incorrect code for the "function"
option:
/*eslint strict: ["error", "function"]*/
"use strict";
function foo() {
// Missing strict mode directive
return function() {
"use strict"; // Unnecessary; parent should contain a strict mode directive
"use strict";
return;
};
}
foo();
Examples of correct code for the "function"
option:
/*eslint strict: ["error", "function"]*/
function foo() {
"use strict";
return function() {
return;
};
}
(function() {
"use strict";
return;
}());
foo();
earlier default (removed)
Replacement notice: This mode, previously enabled by turning on the rule without specifying a mode, has been removed in ESLint v1.0. "function"
mode is most similar to the deprecated behavior.
This mode ensures that all functions are executed in strict mode. A strict mode directive must be present in global code or in every top-level function declaration or expression. It does not concern itself with unnecessary strict mode directives in nested functions that are already strict, nor with multiple strict mode directives at the same level.
Examples of incorrect code for an earlier default option which has been removed:
// "strict": "error"
function foo() {
return true;
}
Examples of correct code for an earlier default option which has been removed:
// "strict": "error"
"use strict";
function foo() {
return true;
}
// "strict": "error"
function foo() {
"use strict";
return true;
}
// "strict": "error"
(function() {
"use strict";
// other code
}());
When Not To Use It
In a codebase that has both strict and non-strict code, either turn this rule off, or selectively disable it where necessary. For example, functions referencing arguments.callee
are invalid in strict mode. A full list of strict mode differences is available on MDN.
Source: http://eslint.org/docs/rules/
'__dirname' is not defined. Open
staticPath: path.resolve(__dirname, localStaticPath),
- Read upRead up
- Exclude checks
Disallow Undeclared Variables (no-undef)
This rule can help you locate potential ReferenceErrors resulting from misspellings of variable and parameter names, or accidental implicit globals (for example, from forgetting the var
keyword in a for
loop initializer).
Rule Details
Any reference to an undeclared variable causes a warning, unless the variable is explicitly mentioned in a /*global ...*/
comment.
Examples of incorrect code for this rule:
/*eslint no-undef: "error"*/
var a = someFunction();
b = 10;
Examples of correct code for this rule with global
declaration:
/*global someFunction b:true*/
/*eslint no-undef: "error"*/
var a = someFunction();
b = 10;
The b:true
syntax in /*global */
indicates that assignment to b
is correct.
Examples of incorrect code for this rule with global
declaration:
/*global b*/
/*eslint no-undef: "error"*/
b = 10;
By default, variables declared in /*global */
are read-only, therefore assignment is incorrect.
Options
-
typeof
set to true will warn for variables used inside typeof check (Default false).
typeof
Examples of correct code for the default { "typeof": false }
option:
/*eslint no-undef: "error"*/
if (typeof UndefinedIdentifier === "undefined") {
// do something ...
}
You can use this option if you want to prevent typeof
check on a variable which has not been declared.
Examples of incorrect code for the { "typeof": true }
option:
/*eslint no-undef: ["error", { "typeof": true }] */
if(typeof a === "string"){}
Examples of correct code for the { "typeof": true }
option with global
declaration:
/*global a*/
/*eslint no-undef: ["error", { "typeof": true }] */
if(typeof a === "string"){}
Environments
For convenience, ESLint provides shortcuts that pre-define global variables exposed by popular libraries and runtime environments. This rule supports these environments, as listed in Specifying Environments. A few examples are given below.
browser
Examples of correct code for this rule with browser
environment:
/*eslint no-undef: "error"*/
/*eslint-env browser*/
setTimeout(function() {
alert("Hello");
});
node
Examples of correct code for this rule with node
environment:
/*eslint no-undef: "error"*/
/*eslint-env node*/
var fs = require("fs");
module.exports = function() {
console.log(fs);
};
When Not To Use It
If explicit declaration of global variables is not to your taste.
Compatibility
This rule provides compatibility with treatment of global variables in JSHint and JSLint.
Further Reading
Missing semicolon. Open
}
- Read upRead up
- Exclude checks
Enforce or Disallow Semicolons (semi)
(fixable) The --fix
option on the [command line](../user-guide/command-line-interface#fix) automatically fixes problems reported by this rule.
JavaScript is unique amongst the C-like languages in that it doesn't require semicolons at the end of each statement. In many cases, the JavaScript engine can determine that a semicolon should be in a certain spot and will automatically add it. This feature is known as automatic semicolon insertion (ASI) and is considered one of the more controversial features of JavaScript. For example, the following lines are both valid:
var name = "ESLint"
var website = "eslint.org";
On the first line, the JavaScript engine will automatically insert a semicolon, so this is not considered a syntax error. The JavaScript engine still knows how to interpret the line and knows that the line end indicates the end of the statement.
In the debate over ASI, there are generally two schools of thought. The first is that we should treat ASI as if it didn't exist and always include semicolons manually. The rationale is that it's easier to always include semicolons than to try to remember when they are or are not required, and thus decreases the possibility of introducing an error.
However, the ASI mechanism can sometimes be tricky to people who are using semicolons. For example, consider this code:
return
{
name: "ESLint"
};
This may look like a return
statement that returns an object literal, however, the JavaScript engine will interpret this code as:
return;
{
name: "ESLint";
}
Effectively, a semicolon is inserted after the return
statement, causing the code below it (a labeled literal inside a block) to be unreachable. This rule and the [no-unreachable](no-unreachable.md) rule will protect your code from such cases.
On the other side of the argument are those who says that since semicolons are inserted automatically, they are optional and do not need to be inserted manually. However, the ASI mechanism can also be tricky to people who don't use semicolons. For example, consider this code:
var globalCounter = { }
(function () {
var n = 0
globalCounter.increment = function () {
return ++n
}
})()
In this example, a semicolon will not be inserted after the first line, causing a run-time error (because an empty object is called as if it's a function). The [no-unexpected-multiline](no-unexpected-multiline.md) rule can protect your code from such cases.
Although ASI allows for more freedom over your coding style, it can also make your code behave in an unexpected way, whether you use semicolons or not. Therefore, it is best to know when ASI takes place and when it does not, and have ESLint protect your code from these potentially unexpected cases. In short, as once described by Isaac Schlueter, a \n
character always ends a statement (just like a semicolon) unless one of the following is true:
- The statement has an unclosed paren, array literal, or object literal or ends in some other way that is not a valid way to end a statement. (For instance, ending with
.
or,
.) - The line is
--
or++
(in which case it will decrement/increment the next token.) - It is a
for()
,while()
,do
,if()
, orelse
, and there is no{
- The next line starts with
[
,(
,+
,*
,/
,-
,,
,.
, or some other binary operator that can only be found between two tokens in a single expression.
Rule Details
This rule is aimed at ensuring consistent use of semicolons. You can decide whether or not to require semicolons at the end of statements.
Options
The rule takes one or two options. The first one is a string, which could be "always"
or "never"
. The default is "always"
. The second one is an object for more fine-grained configuration when the first option is "always"
.
You can set the option in configuration like this:
"always"
By using the default option, semicolons must be used any place where they are valid.
semi: ["error", "always"]
The following patterns are considered problems:
/*eslint semi: "error"*/
var name = "ESLint"
object.method = function() {
// ...
}
The following patterns are not considered problems:
/*eslint semi: "error"*/
var name = "ESLint";
object.method = function() {
// ...
};
Fine-grained control
When setting the first option as "always", an additional option can be added to omit the last semicolon in a one-line block, that is, a block in which its braces (and therefore the content of the block) are in the same line:
semi: ["error", "always", { "omitLastInOneLineBlock": true}]
The following patterns are considered problems:
/*eslint semi: ["error", "always", { "omitLastInOneLineBlock": true}] */
if (foo) {
bar()
}
if (foo) { bar(); }
The following patterns are not considered problems:
/*eslint semi: ["error", "always", { "omitLastInOneLineBlock": true}] */
if (foo) { bar() }
if (foo) { bar(); baz() }
"never"
If you want to enforce that semicolons are never used, switch the configuration to:
semi: [2, "never"]
Then, the following patterns are considered problems:
/*eslint semi: ["error", "never"]*/
var name = "ESLint";
object.method = function() {
// ...
};
And the following patterns are not considered problems:
/*eslint semi: ["error", "never"]*/
var name = "ESLint"
object.method = function() {
// ...
}
Even in "never"
mode, semicolons are still allowed to disambiguate statements beginning with [
, (
, /
, +
, or -
:
/*eslint semi: ["error", "never"]*/
var name = "ESLint"
;(function() {
// ...
})()
When Not To Use It
If you do not want to enforce semicolon usage (or omission) in any particular way, then you can turn this rule off.
Further Reading
- An Open Letter to JavaScript Leaders Regarding Semicolons
- JavaScript Semicolon Insertion
- Understanding Automatic Semicolon Insertion in JavaScript
Related Rules
- [no-extra-semi](no-extra-semi.md)
- [no-unexpected-multiline](no-unexpected-multiline.md)
- [semi-spacing](semi-spacing.md) Source: http://eslint.org/docs/rules/
Missing semicolon. Open
}
- Read upRead up
- Exclude checks
Enforce or Disallow Semicolons (semi)
(fixable) The --fix
option on the [command line](../user-guide/command-line-interface#fix) automatically fixes problems reported by this rule.
JavaScript is unique amongst the C-like languages in that it doesn't require semicolons at the end of each statement. In many cases, the JavaScript engine can determine that a semicolon should be in a certain spot and will automatically add it. This feature is known as automatic semicolon insertion (ASI) and is considered one of the more controversial features of JavaScript. For example, the following lines are both valid:
var name = "ESLint"
var website = "eslint.org";
On the first line, the JavaScript engine will automatically insert a semicolon, so this is not considered a syntax error. The JavaScript engine still knows how to interpret the line and knows that the line end indicates the end of the statement.
In the debate over ASI, there are generally two schools of thought. The first is that we should treat ASI as if it didn't exist and always include semicolons manually. The rationale is that it's easier to always include semicolons than to try to remember when they are or are not required, and thus decreases the possibility of introducing an error.
However, the ASI mechanism can sometimes be tricky to people who are using semicolons. For example, consider this code:
return
{
name: "ESLint"
};
This may look like a return
statement that returns an object literal, however, the JavaScript engine will interpret this code as:
return;
{
name: "ESLint";
}
Effectively, a semicolon is inserted after the return
statement, causing the code below it (a labeled literal inside a block) to be unreachable. This rule and the [no-unreachable](no-unreachable.md) rule will protect your code from such cases.
On the other side of the argument are those who says that since semicolons are inserted automatically, they are optional and do not need to be inserted manually. However, the ASI mechanism can also be tricky to people who don't use semicolons. For example, consider this code:
var globalCounter = { }
(function () {
var n = 0
globalCounter.increment = function () {
return ++n
}
})()
In this example, a semicolon will not be inserted after the first line, causing a run-time error (because an empty object is called as if it's a function). The [no-unexpected-multiline](no-unexpected-multiline.md) rule can protect your code from such cases.
Although ASI allows for more freedom over your coding style, it can also make your code behave in an unexpected way, whether you use semicolons or not. Therefore, it is best to know when ASI takes place and when it does not, and have ESLint protect your code from these potentially unexpected cases. In short, as once described by Isaac Schlueter, a \n
character always ends a statement (just like a semicolon) unless one of the following is true:
- The statement has an unclosed paren, array literal, or object literal or ends in some other way that is not a valid way to end a statement. (For instance, ending with
.
or,
.) - The line is
--
or++
(in which case it will decrement/increment the next token.) - It is a
for()
,while()
,do
,if()
, orelse
, and there is no{
- The next line starts with
[
,(
,+
,*
,/
,-
,,
,.
, or some other binary operator that can only be found between two tokens in a single expression.
Rule Details
This rule is aimed at ensuring consistent use of semicolons. You can decide whether or not to require semicolons at the end of statements.
Options
The rule takes one or two options. The first one is a string, which could be "always"
or "never"
. The default is "always"
. The second one is an object for more fine-grained configuration when the first option is "always"
.
You can set the option in configuration like this:
"always"
By using the default option, semicolons must be used any place where they are valid.
semi: ["error", "always"]
The following patterns are considered problems:
/*eslint semi: "error"*/
var name = "ESLint"
object.method = function() {
// ...
}
The following patterns are not considered problems:
/*eslint semi: "error"*/
var name = "ESLint";
object.method = function() {
// ...
};
Fine-grained control
When setting the first option as "always", an additional option can be added to omit the last semicolon in a one-line block, that is, a block in which its braces (and therefore the content of the block) are in the same line:
semi: ["error", "always", { "omitLastInOneLineBlock": true}]
The following patterns are considered problems:
/*eslint semi: ["error", "always", { "omitLastInOneLineBlock": true}] */
if (foo) {
bar()
}
if (foo) { bar(); }
The following patterns are not considered problems:
/*eslint semi: ["error", "always", { "omitLastInOneLineBlock": true}] */
if (foo) { bar() }
if (foo) { bar(); baz() }
"never"
If you want to enforce that semicolons are never used, switch the configuration to:
semi: [2, "never"]
Then, the following patterns are considered problems:
/*eslint semi: ["error", "never"]*/
var name = "ESLint";
object.method = function() {
// ...
};
And the following patterns are not considered problems:
/*eslint semi: ["error", "never"]*/
var name = "ESLint"
object.method = function() {
// ...
}
Even in "never"
mode, semicolons are still allowed to disambiguate statements beginning with [
, (
, /
, +
, or -
:
/*eslint semi: ["error", "never"]*/
var name = "ESLint"
;(function() {
// ...
})()
When Not To Use It
If you do not want to enforce semicolon usage (or omission) in any particular way, then you can turn this rule off.
Further Reading
- An Open Letter to JavaScript Leaders Regarding Semicolons
- JavaScript Semicolon Insertion
- Understanding Automatic Semicolon Insertion in JavaScript
Related Rules
- [no-extra-semi](no-extra-semi.md)
- [no-unexpected-multiline](no-unexpected-multiline.md)
- [semi-spacing](semi-spacing.md) Source: http://eslint.org/docs/rules/
Unnecessarily quoted property 'NODE_ENV' found. Open
'NODE_ENV': 'development'
- Read upRead up
- Exclude checks
Quoting Style for Property Names (quote-props)
Object literal property names can be defined in two ways: using literals or using strings. For example, these two objects are equivalent:
var object1 = {
property: true
};
var object2 = {
"property": true
};
In many cases, it doesn't matter if you choose to use an identifier instead of a string or vice-versa. Even so, you might decide to enforce a consistent style in your code.
There are, however, some occasions when you must use quotes:
- If you are using an ECMAScript 3 JavaScript engine (such as IE8) and you want to use a keyword (such as
if
) as a property name. This restriction was removed in ECMAScript 5. - You want to use a non-identifier character in your property name, such as having a property with a space like
"one two"
.
Another example where quotes do matter is when using numeric literals as property keys:
var object = {
1e2: 1,
100: 2
};
This may look alright at first sight, but this code in fact throws a syntax error in ECMAScript 5 strict mode. This happens because 1e2
and 100
are coerced into strings before getting used as the property name. Both String(1e2)
and String(100)
happen to be equal to "100"
, which causes the "Duplicate data property in object literal not allowed in strict mode" error. Issues like that can be tricky to debug, so some prefer to require quotes around all property names.
Rule Details
This rule aims to enforce use of quotes in property names and as such will flag any properties that don't use quotes (default behavior).
Options
There are four behaviors for this rule: "always"
(default), "as-needed"
, "consistent"
and "consistent-as-needed"
. You can define these options in your configuration as:
{
"quote-props": ["error", "as-needed"]
}
"always"
When configured with "always"
as the first option (the default), quoting for all properties will be enforced. Some believe that ensuring property names in object literals are always wrapped in quotes is generally a good idea, since depending on the property name you may need to quote them anyway. Consider this example:
var object = {
foo: "bar",
baz: 42,
"qux-lorem": true
};
Here, the properties foo
and baz
are not wrapped in quotes, but qux-lorem
is, because it doesn’t work without the quotes. This is rather inconsistent. Instead, you may prefer to quote names of all properties:
var object = {
"foo": "bar",
"baz": 42,
"qux-lorem": true
};
or, if you prefer single quotes:
var object = {
'foo': 'bar',
'baz': 42,
'qux-lorem': true
};
When configured with "always"
as the first option (the default), quoting for all properties will be enforced. The following patterns are considered problems:
/*eslint quote-props: ["error", "always"]*/
var object = {
foo: "bar",
baz: 42,
"qux-lorem": true
};
The following patterns are not considered problems:
/*eslint quote-props: ["error", "always"]*/
/*eslint-env es6*/
var object1 = {
"foo": "bar",
"baz": 42,
"qux-lorem": true
};
var object2 = {
'foo': 'bar',
'baz': 42,
'qux-lorem': true
};
var object3 = {
foo() {
return;
}
};
"as-needed"
When configured with "as-needed"
as the first option, quotes will be enforced when they are strictly required, and unnecessary quotes will cause warnings. The following patterns are considered problems:
/*eslint quote-props: ["error", "as-needed"]*/
var object = {
"a": 0,
"0": 0,
"true": 0,
"null": 0
};
The following patterns are not considered problems:
/*eslint quote-props: ["error", "as-needed"]*/
/*eslint-env es6*/
var object1 = {
"a-b": 0,
"0x0": 0,
"1e2": 0
};
var object2 = {
foo: 'bar',
baz: 42,
true: 0,
0: 0,
'qux-lorem': true
};
var object3 = {
foo() {
return;
}
};
When the "as-needed"
mode is selected, an additional keywords
option can be provided. This flag indicates whether language keywords should be quoted as properties. By default it is set to false
.
{
"quote-props": ["error", "as-needed", { "keywords": true }]
}
When keywords
is set to true
, the following patterns become problems:
/*eslint quote-props: ["error", "as-needed", { "keywords": true }]*/
var x = {
while: 1,
volatile: "foo"
};
Another modifier for this rule is the unnecessary
option which defaults to true
. Setting this to false
will prevent the rule from complaining about unnecessarily quoted properties. This comes in handy when you only care about quoting keywords.
{
"quote-props": ["error", "as-needed", { "keywords": true, "unnecessary": false }]
}
When unnecessary
is set to false
, the following patterns stop being problems:
/*eslint quote-props: ["error", "as-needed", { "keywords": true, "unnecessary": false }]*/
var x = {
"while": 1,
"foo": "bar" // Would normally have caused a warning
};
A numbers
flag, with default value false
, can also be used as a modifier for the "as-needed"
mode. When it is set to true
, numeric literals should always be quoted.
{
"quote-props": ["error", "as-needed", {"numbers": true}]
}
When numbers
is set to true
, the following patterns become problems:
/*eslint quote-props: ["error", "as-needed", { "numbers": true }]*/
var x = {
100: 1
}
and the following patterns stop being problems:
var x = {
"100": 1
}
"consistent"
When configured with "consistent"
, the patterns below are considered problems. Basically "consistent"
means all or no properties are expected to be quoted, in other words quoting style can't be mixed within an object. Please note the latter situation (no quotation at all) isn't always possible as some property names require quoting.
/*eslint quote-props: ["error", "consistent"]*/
var object1 = {
foo: "bar",
"baz": 42,
"qux-lorem": true
};
var object2 = {
'foo': 'bar',
baz: 42
};
The following patterns are not considered problems:
/*eslint quote-props: ["error", "consistent"]*/
var object1 = {
"foo": "bar",
"baz": 42,
"qux-lorem": true
};
var object2 = {
'foo': 'bar',
'baz': 42
};
var object3 = {
foo: 'bar',
baz: 42
};
"consistent-as-needed"
When configured with "consistent-as-needed"
, the behavior is similar to "consistent"
with one difference. Namely, properties' quoting should be consistent (as in "consistent"
) but whenever all quotes are redundant a warning is raised. In other words if at least one property name has to be quoted (like qux-lorem
) then all property names must be quoted, otherwise no properties can be quoted. The following patterns are considered problems:
/*eslint quote-props: ["error", "consistent-as-needed"]*/
var object1 = {
foo: "bar",
"baz": 42,
"qux-lorem": true
};
var object2 = {
'foo': 'bar',
'baz': 42
};
The following patterns are not considered problems:
/*eslint quote-props: ["error", "consistent-as-needed"]*/
var object1 = {
"foo": "bar",
"baz": 42,
"qux-lorem": true
};
var object2 = {
foo: 'bar',
baz: 42
};
When the "consistent-as-needed"
mode is selected, an additional keywords
option can be provided. This flag indicates whether language keywords can be used unquoted as properties. By default it is set to false
.
{
"quote-props": ["error", "consistent-as-needed", { "keywords": true }]
}
When keywords
is set to true
, the following patterns are considered problems:
/*eslint quote-props: ["error", "consistent-as-needed", { "keywords": true }]*/
var x = {
while: 1,
volatile: "foo"
};
When Not To Use It
If you don't care if property names are consistently wrapped in quotes or not, and you don't target legacy ES3 environments, turn this rule off.
Further Reading
Closing curly brace does not appear on the same line as the subsequent block. Open
else {
- Read upRead up
- Exclude checks
Require Brace Style (brace-style)
Brace style is closely related to indent style in programming and describes the placement of braces relative to their control statement and body. There are probably a dozen, if not more, brace styles in the world.
The one true brace style is one of the most common brace styles in JavaScript, in which the opening brace of a block is placed on the same line as its corresponding statement or declaration. For example:
if (foo) {
bar();
} else {
baz();
}
One common variant of one true brace style is called Stroustrup, in which the else
statements in an if-else
construct, as well as catch
and finally
, must be on its own line after the preceding closing brace. For example:
if (foo) {
bar();
}
else {
baz();
}
Another style is called Allman, in which all the braces are expected to be on their own lines without any extra indentation. For example:
if (foo)
{
bar();
}
else
{
baz();
}
While no style is considered better than the other, most developers agree that having a consistent style throughout a project is important for its long-term maintainability.
Rule Details
This rule enforces consistent brace style for blocks.
Options
This rule has a string option:
-
"1tbs"
(default) enforces one true brace style -
"stroustrup"
enforces Stroustrup style -
"allman"
enforces Allman style
This rule has an object option for an exception:
-
"allowSingleLine": true
(defaultfalse
) allows the opening and closing braces for a block to be on the same line
1tbs
Examples of incorrect code for this rule with the default "1tbs"
option:
/*eslint brace-style: "error"*/
function foo()
{
return true;
}
if (foo)
{
bar();
}
try
{
somethingRisky();
} catch(e)
{
handleError();
}
if (foo) {
bar();
}
else {
baz();
}
Examples of correct code for this rule with the default "1tbs"
option:
/*eslint brace-style: "error"*/
function foo() {
return true;
}
if (foo) {
bar();
}
if (foo) {
bar();
} else {
baz();
}
try {
somethingRisky();
} catch(e) {
handleError();
}
// when there are no braces, there are no problems
if (foo) bar();
else if (baz) boom();
Examples of correct code for this rule with the "1tbs", { "allowSingleLine": true }
options:
/*eslint brace-style: ["error", "1tbs", { "allowSingleLine": true }]*/
function nop() { return; }
if (foo) { bar(); }
if (foo) { bar(); } else { baz(); }
try { somethingRisky(); } catch(e) { handleError(); }
stroustrup
Examples of incorrect code for this rule with the "stroustrup"
option:
/*eslint brace-style: ["error", "stroustrup"]*/
function foo()
{
return true;
}
if (foo)
{
bar();
}
try
{
somethingRisky();
} catch(e)
{
handleError();
}
if (foo) {
bar();
} else {
baz();
}
Examples of correct code for this rule with the "stroustrup"
option:
/*eslint brace-style: ["error", "stroustrup"]*/
function foo() {
return true;
}
if (foo) {
bar();
}
if (foo) {
bar();
}
else {
baz();
}
try {
somethingRisky();
}
catch(e) {
handleError();
}
// when there are no braces, there are no problems
if (foo) bar();
else if (baz) boom();
Examples of correct code for this rule with the "stroustrup", { "allowSingleLine": true }
options:
/*eslint brace-style: ["error", "stroustrup", { "allowSingleLine": true }]*/
function nop() { return; }
if (foo) { bar(); }
if (foo) { bar(); }
else { baz(); }
try { somethingRisky(); }
catch(e) { handleError(); }
allman
Examples of incorrect code for this rule with the "allman"
option:
/*eslint brace-style: ["error", "allman"]*/
function foo() {
return true;
}
if (foo)
{
bar(); }
try
{
somethingRisky();
} catch(e)
{
handleError();
}
if (foo) {
bar();
} else {
baz();
}
Examples of correct code for this rule with the "allman"
option:
/*eslint brace-style: ["error", "allman"]*/
function foo()
{
return true;
}
if (foo)
{
bar();
}
if (foo)
{
bar();
}
else
{
baz();
}
try
{
somethingRisky();
}
catch(e)
{
handleError();
}
// when there are no braces, there are no problems
if (foo) bar();
else if (baz) boom();
Examples of correct code for this rule with the "allman", { "allowSingleLine": true }
options:
/*eslint brace-style: ["error", "allman", { "allowSingleLine": true }]*/
function nop() { return; }
if (foo) { bar(); }
if (foo) { bar(); }
else { baz(); }
try { somethingRisky(); }
catch(e) { handleError(); }
When Not To Use It
If your project will not be using the one true brace style, turn this rule off.
Further Reading
A space is required after '{' Open
this.body = {success: true};
- Read upRead up
- Exclude checks
Disallow or enforce spaces inside of curly braces in objects. (object-curly-spacing)
(fixable) The --fix
option on the [command line](../user-guide/command-line-interface#fix) automatically fixes problems reported by this rule.
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 aims to maintain consistency around the spacing inside of object literals. It also applies to EcmaScript 6 destructured assignment and import/export specifiers.
It either requires or disallows spaces between those braces and the values inside of them. Braces that are separated from the adjacent value by a new line are exempt from this rule.
Options
There are two main options for the rule:
-
"always"
enforces a space inside of curly braces -
"never"
disallows spaces inside of curly braces (default)
Depending on your coding conventions, you can choose either option by specifying it in your configuration:
"object-curly-spacing": ["error", "always"]
"never"
When "never"
is set, the following patterns are considered problems:
/*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';
The following patterns are not considered problems:
/*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"
When "always"
is used, the following patterns are considered problems:
/*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';
The following patterns are not considered problems:
/*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';
Note that {}
is always exempt from spacing requirements with this rule.
Exceptions
There are two exceptions you can apply to this rule: objectsInObjects
and
arraysInObjects
. Their values can be set to either true
or false
as part
of an object literal set as the 3rd argument for the rule.
These exceptions work in the context of the first option.
That is, if "always"
is set to enforce spacing and an exception is set to false
,
it will disallow spacing for cases matching the exception. Likewise,
if "never"
is set to disallow spacing and an exception is set to true
,
it will enforce spacing for cases matching the exception.
You can add exceptions like so:
"object-curly-spacing": ["error", "always", {
"objectsInObjects": false,
"arraysInObjects": false
}]
objectsInObjects
In the case of the "always"
option, set objectsInObjects
exception to false
to
enforce the following syntax (notice the }}
at the end):
var obj = { "foo": { "baz": 1, "bar": 2 }};
In the case of the "never"
option, set objectsInObjects
exception to true
to enforce
the following style (with a space between the }
at the end:
var obj = {"foo": {"baz": 1, "bar": 2} };
arraysInObjects
In the case of the "always"
option, set arraysInObjects
exception to false
to
enforce the following syntax (notice the ]}
at the end):
var obj = { "foo": [ 1, 2 ]};
var obj = { "foo": [ "baz", "bar" ]};
In the case of the "never"
option, set arraysInObjects
exception to true
to enforce
the following style (with a space between the ]
and }
at the end:
var obj = {"foo": [ 1, 2 ] };
var obj = {"foo": [ "baz", "bar" ] };
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)
- [space-in-brackets](space-in-brackets.md) (deprecated) Source: http://eslint.org/docs/rules/
Unexpected function expression. Open
gulp.task('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/