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".
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.
ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let
and const keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes
such as:
var count = people.length;
var enoughFood = count > sandwiches.length;
if(enoughFood){
var count = sandwiches.length;// accidentally overriding the count variable
console.log("We have "+ count +" sandwiches for everyone. Plenty for all!");
}
// our count variable is no longer accurate
console.log("We have "+ count +" people and "+ sandwiches.length +" sandwiches!");
Rule Details
This rule is aimed at discouraging the use of var and encouraging the use of const or let instead.
Examples
Examples of incorrect code for this rule:
/*eslint no-var: "error"*/
var x ="y";
varCONFIG={};
Examples of correct code for this rule:
/*eslint no-var: "error"*/
/*eslint-env es6*/
let x ="y";
constCONFIG={};
When Not To Use It
In addition to non-ES6 environments, existing JavaScript projects that are beginning to introduce ES6 into their
codebase may not want to apply this rule if the cost of migrating from var to let is too costly.
Source: http://eslint.org/docs/rules/
enforce consistent spacing between keys and values in object literal properties (key-spacing)
This rule enforces spacing around the colon in object literal properties. It can verify each property individually, or it can ensure horizontal alignment of adjacent properties in an object literal.
Rule Details
This rule enforces consistent spacing between keys and values in object literal properties. In the case of long lines, it is acceptable to add a new line wherever whitespace is allowed.
Options
This rule has an object option:
"beforeColon": false (default) disallows spaces between the key and the colon in object literals.
"beforeColon": true requires at least one space between the key and the colon in object literals.
"afterColon": true (default) requires at least one space between the colon and the value in object literals.
"afterColon": false disallows spaces between the colon and the value in object literals.
"mode": "strict" (default) enforces exactly one space before or after colons in object literals.
"mode": "minimum" enforces one or more spaces before or after colons in object literals.
"align": "value" enforces horizontal alignment of values in object literals.
"align": "colon" enforces horizontal alignment of both colons and values in object literals.
"align" with an object value allows for fine-grained spacing when values are being aligned in object literals.
"singleLine" specifies a spacing style for single-line object literals.
"multiLine" specifies a spacing style for multi-line object literals.
Please note that you can either use the top-level options or the grouped options (singleLine and multiLine) but not both.
beforeColon
Examples of incorrect code for this rule with the default { "beforeColon": false } option:
The align option can take additional configuration through the beforeColon, afterColon, mode, and on options.
If align is defined as an object, but not all of the parameters are provided, undefined parameters will default to the following:
// Defaults
align:{
"beforeColon":false,
"afterColon":true,
"on":"colon",
"mode":"strict"
}
Examples of correct code for this rule with sample { "align": { } } options:
/*eslint key-spacing: ["error", {
"align": {
"beforeColon": true,
"afterColon": true,
"on": "colon"
}
}]*/
var obj ={
"one":1,
"seven":7
}
/*eslint key-spacing: ["error", {
"align": {
"beforeColon": false,
"afterColon": false,
"on": "value"
}
}]*/
var obj ={
"one":1,
"seven":7
}
align and multiLine
The multiLine and align options can differ, which allows for fine-tuned control over the key-spacing of your files. align will not inherit from multiLine if align is configured as an object.
multiLine is used any time an object literal spans multiple lines. The align configuration is used when there is a group of properties in the same object. For example:
var myObj ={
key1:1,// uses multiLine
key2:2,// uses align (when defined)
key3:3,// uses align (when defined)
key4:4// uses multiLine
}
Examples of incorrect code for this rule with sample { "align": { }, "multiLine": { } } options:
/*eslint key-spacing: ["error", {
"multiLine": {
"beforeColon": false,
"afterColon":true
},
"align": {
"beforeColon": true,
"afterColon": true,
"on": "colon"
}
}]*/
var obj ={
"myObjectFunction":function(){
// Do something
},
"one":1,
"seven":7
}
Examples of correct code for this rule with sample { "align": { }, "multiLine": { } } options:
/*eslint key-spacing: ["error", {
"multiLine": {
"beforeColon": false,
"afterColon": true
},
"align": {
"beforeColon": true,
"afterColon": true,
"on": "colon"
}
}]*/
var obj ={
"myObjectFunction":function(){
// Do something
//
},// These are two separate groups, so no alignment between `myObjectFuction` and `one`
"one":1,
"seven":7// `one` and `seven` are in their own group, and therefore aligned
}
singleLine and multiLine
Examples of correct code for this rule with sample { "singleLine": { }, "multiLine": { } } options:
/*eslint "key-spacing": [2, {
"singleLine": {
"beforeColon": false,
"afterColon": true
},
"multiLine": {
"beforeColon": true,
"afterColon": true,
"align": "colon"
}
}]*/
var obj ={one:1,"two":2,three:3};
var obj2 ={
"two":2,
three:3
};
When Not To Use It
If you have another convention for property spacing that might not be consistent with the available options, or if you want to permit multiple styles concurrently you can safely disable this rule.
Source: http://eslint.org/docs/rules/
disallow dangling underscores in identifiers (no-underscore-dangle)
As far as naming conventions for identifiers go, dangling underscores may be the most polarizing in JavaScript. Dangling underscores are underscores at either the beginning or end of an identifier, such as:
var _foo;
There is actually a long history of using dangling underscores to indicate "private" members of objects in JavaScript (though JavaScript doesn't have truly private members, this convention served as a warning). This began with SpiderMonkey adding nonstandard methods such as __defineGetter__(). The intent with the underscores was to make it obvious that this method was special in some way. Since that time, using a single underscore prefix has become popular as a way to indicate "private" members of objects.
Whether or not you choose to allow dangling underscores in identifiers is purely a convention and has no effect on performance, readability, or complexity. It's purely a preference.
Rule Details
This rule disallows dangling underscores in identifiers.
Examples of incorrect code for this rule:
/*eslint no-underscore-dangle: "error"*/
var foo_;
var __proto__ ={};
foo._bar();
Examples of correct code for this rule:
/*eslint no-underscore-dangle: "error"*/
var _ =require('underscore');
var obj = _.contains(items, item);
obj.__proto__ ={};
var file = __filename;
Options
This rule has an object option:
"allow" allows specified identifiers to have dangling underscores
"allowAfterThis": false (default) disallows dangling underscores in members of the this object
"allowAfterSuper": false (default) disallows dangling underscores in members of the super object
allow
Examples of additional correct code for this rule with the { "allow": ["foo_", "_bar"] } option:
If you want to allow dangling underscores in identifiers, then you can safely turn this rule off.
Source: http://eslint.org/docs/rules/
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:
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.
require or disallow trailing commas (comma-dangle)
Trailing commas in object literals are valid according to the ECMAScript 5 (and ECMAScript 3!) spec. However, IE8 (when not in IE8 document mode) and below will throw an error when it encounters trailing commas in JavaScript.
var foo ={
bar:"baz",
qux:"quux",
};
Trailing commas simplify adding and removing items to objects and arrays, since only the lines you are modifying must be touched.
Another argument in favor of trailing commas is that it improves the clarity of diffs when an item is added or removed from an object or array:
Less clear:
var foo = {
- bar: "baz",
- qux: "quux"
+ bar: "baz"
};
More clear:
var foo = {
bar: "baz",
- qux: "quux",
};
Rule Details
This rule enforces consistent use of trailing commas in object and array literals.
Options
This rule has a string option or an object option:
{
"comma-dangle": ["error", "never"],
// or
"comma-dangle": ["error", {
"arrays": "never",
"objects": "never",
"imports": "never",
"exports": "never",
"functions": "ignore",
}]
}
"never" (default) disallows trailing commas
"always" requires trailing commas
"always-multiline" requires trailing commas when the last element or property is in a different line than the closing ] or } and disallows trailing commas when the last element or property is on the same line as the closing ] or }
"only-multiline" allows (but does not require) trailing commas when the last element or property is in a different line than the closing ] or } and disallows trailing commas when the last element or property is on the same line as the closing ] or }
Trailing commas in function declarations and function calls are valid syntax since ECMAScript 2017; however, the string option does not check these situations for backwards compatibility.
You can also use an object option to configure this rule for each type of syntax.
Each of the following options can be set to "never", "always", "always-multiline", "only-multiline", or "ignore".
The default for each option is "never" unless otherwise specified.
arrays is for array literals and array patterns of destructuring. (e.g. let [a,] = [1,];)
objects is for object literals and object patterns of destructuring. (e.g. let {a,} = {a: 1};)
imports is for import declarations of ES Modules. (e.g. import {a,} from "foo";)
exports is for export declarations of ES Modules. (e.g. export {a,};)
functions is for function declarations and function calls. (e.g. (function(a,){ })(b,);) functions is set to "ignore" by default for consistency with the string option.
never
Examples of incorrect code for this rule with the default "never" option:
/*eslint comma-dangle: ["error", "never"]*/
var foo ={
bar:"baz",
qux:"quux",
};
var arr =[1,2,];
foo({
bar:"baz",
qux:"quux",
});
Examples of correct code for this rule with the default "never" option:
/*eslint comma-dangle: ["error", "never"]*/
var foo ={
bar:"baz",
qux:"quux"
};
var arr =[1,2];
foo({
bar:"baz",
qux:"quux"
});
always
Examples of incorrect code for this rule with the "always" option:
/*eslint comma-dangle: ["error", "always"]*/
var foo ={
bar:"baz",
qux:"quux"
};
var arr =[1,2];
foo({
bar:"baz",
qux:"quux"
});
Examples of correct code for this rule with the "always" option:
/*eslint comma-dangle: ["error", "always"]*/
var foo ={
bar:"baz",
qux:"quux",
};
var arr =[1,2,];
foo({
bar:"baz",
qux:"quux",
});
always-multiline
Examples of incorrect code for this rule with the "always-multiline" option:
There are several common guidelines which require specific indentation of nested blocks and statements, like:
functionhello(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;
functionfoo(d){
e=f;
}
}
Examples of correct code for this rule with the default options:
/*eslint indent: "error"*/
if(a){
b=c;
functionfoo(d){
e=f;
}
}
This rule has an object option:
"SwitchCase" (default: 0) enforces indentation level for case clauses in switch statements
"VariableDeclarator" (default: 1) enforces indentation level for var declarators; can also take an object to define separate rules for var, let and const 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 to 2 will indent the multi-line variable declarations with 8 spaces.
Indent of 2 spaces with VariableDeclarator set to 2 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 for var and let, 6 spaces for const statements.
Indent of tab with VariableDeclarator set to 2 will indent the multi-line variable declarations with 2 tabs.
Indent of 2 spaces with SwitchCase set to 0 will not indent case clauses with respect to switch statements.
Indent of 2 spaces with SwitchCase set to 1 will indent case clauses with 2 spaces with respect to switch statements.
Indent of 2 spaces with SwitchCase set to 2 will indent case clauses with 4 spaces with respect to switch statements.
Indent of tab with SwitchCase set to 2 will indent case clauses with 2 tabs with respect to switch statements.
Indent of 2 spaces with MemberExpression set to 0 will indent the multi-line property chains with 0 spaces.
Indent of 2 spaces with MemberExpression set to 1 will indent the multi-line property chains with 2 spaces.
Indent of 2 spaces with MemberExpression set to 2 will indent the multi-line property chains with 4 spaces.
Indent of 4 spaces with MemberExpression set to 0 will indent the multi-line property chains with 0 spaces.
Indent of 4 spaces with MemberExpression set to 1 will indent the multi-line property chains with 4 spaces.
Indent of 4 spaces with MemberExpression set to 2 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;
functionfoo(d){
e=f;
}
}
Examples of correct code for this rule with the "tab" option:
/*eslint indent: ["error", "tab"]*/
if(a){
/*tab*/b=c;
/*tab*/functionfoo(d){
/*tab*//*tab*/e=f;
/*tab*/}
}
SwitchCase
Examples of incorrect code for this rule with the 2, { "SwitchCase": 1 } options:
disallow dangling underscores in identifiers (no-underscore-dangle)
As far as naming conventions for identifiers go, dangling underscores may be the most polarizing in JavaScript. Dangling underscores are underscores at either the beginning or end of an identifier, such as:
var _foo;
There is actually a long history of using dangling underscores to indicate "private" members of objects in JavaScript (though JavaScript doesn't have truly private members, this convention served as a warning). This began with SpiderMonkey adding nonstandard methods such as __defineGetter__(). The intent with the underscores was to make it obvious that this method was special in some way. Since that time, using a single underscore prefix has become popular as a way to indicate "private" members of objects.
Whether or not you choose to allow dangling underscores in identifiers is purely a convention and has no effect on performance, readability, or complexity. It's purely a preference.
Rule Details
This rule disallows dangling underscores in identifiers.
Examples of incorrect code for this rule:
/*eslint no-underscore-dangle: "error"*/
var foo_;
var __proto__ ={};
foo._bar();
Examples of correct code for this rule:
/*eslint no-underscore-dangle: "error"*/
var _ =require('underscore');
var obj = _.contains(items, item);
obj.__proto__ ={};
var file = __filename;
Options
This rule has an object option:
"allow" allows specified identifiers to have dangling underscores
"allowAfterThis": false (default) disallows dangling underscores in members of the this object
"allowAfterSuper": false (default) disallows dangling underscores in members of the super object
allow
Examples of additional correct code for this rule with the { "allow": ["foo_", "_bar"] } option:
If you want to allow dangling underscores in identifiers, then you can safely turn this rule off.
Source: http://eslint.org/docs/rules/
Disallow Early Use (no-use-before-define)
In JavaScript, prior to ES6, variable and function declarations are hoisted to the top of a scope, so it's possible to use identifiers before their formal declarations in code. This can be confusing and some believe it is best to always declare variables and functions before using them.
In ES6, block-level bindings (let and const) introduce a "temporal dead zone" where a ReferenceError will be thrown with any attempt to access the variable before its declaration.
Rule Details
This rule will warn when it encounters a reference to an identifier that has not yet been declared.
functions (boolean) -
The flag which shows whether or not this rule checks function declarations.
If this is true, this rule warns every reference to a function before the function declaration.
Otherwise, ignores those references.
Function declarations are hoisted, so it's safe.
Default is true.
classes (boolean) -
The flag which shows whether or not this rule checks class declarations of upper scopes.
If this is true, this rule warns every reference to a class before the class declaration.
Otherwise, ignores those references if the declaration is in upper function scopes.
Class declarations are not hoisted, so it might be danger.
Default is true.
variables (boolean) -
This flag determines whether or not the rule checks variable declarations in upper scopes.
If this is true, the rule warns every reference to a variable before the variable declaration.
Otherwise, the rule ignores a reference if the declaration is in an upper scope, while still reporting the reference if it's in the same scope as the declaration.
Default is true.
This rule accepts "nofunc" string as an option.
"nofunc" is the same as { "functions": false, "classes": true }.
functions
Examples of correct code for the { "functions": false } option:
ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let
and const keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes
such as:
var count = people.length;
var enoughFood = count > sandwiches.length;
if(enoughFood){
var count = sandwiches.length;// accidentally overriding the count variable
console.log("We have "+ count +" sandwiches for everyone. Plenty for all!");
}
// our count variable is no longer accurate
console.log("We have "+ count +" people and "+ sandwiches.length +" sandwiches!");
Rule Details
This rule is aimed at discouraging the use of var and encouraging the use of const or let instead.
Examples
Examples of incorrect code for this rule:
/*eslint no-var: "error"*/
var x ="y";
varCONFIG={};
Examples of correct code for this rule:
/*eslint no-var: "error"*/
/*eslint-env es6*/
let x ="y";
constCONFIG={};
When Not To Use It
In addition to non-ES6 environments, existing JavaScript projects that are beginning to introduce ES6 into their
codebase may not want to apply this rule if the cost of migrating from var to let is too costly.
Source: http://eslint.org/docs/rules/
disallow dangling underscores in identifiers (no-underscore-dangle)
As far as naming conventions for identifiers go, dangling underscores may be the most polarizing in JavaScript. Dangling underscores are underscores at either the beginning or end of an identifier, such as:
var _foo;
There is actually a long history of using dangling underscores to indicate "private" members of objects in JavaScript (though JavaScript doesn't have truly private members, this convention served as a warning). This began with SpiderMonkey adding nonstandard methods such as __defineGetter__(). The intent with the underscores was to make it obvious that this method was special in some way. Since that time, using a single underscore prefix has become popular as a way to indicate "private" members of objects.
Whether or not you choose to allow dangling underscores in identifiers is purely a convention and has no effect on performance, readability, or complexity. It's purely a preference.
Rule Details
This rule disallows dangling underscores in identifiers.
Examples of incorrect code for this rule:
/*eslint no-underscore-dangle: "error"*/
var foo_;
var __proto__ ={};
foo._bar();
Examples of correct code for this rule:
/*eslint no-underscore-dangle: "error"*/
var _ =require('underscore');
var obj = _.contains(items, item);
obj.__proto__ ={};
var file = __filename;
Options
This rule has an object option:
"allow" allows specified identifiers to have dangling underscores
"allowAfterThis": false (default) disallows dangling underscores in members of the this object
"allowAfterSuper": false (default) disallows dangling underscores in members of the super object
allow
Examples of additional correct code for this rule with the { "allow": ["foo_", "_bar"] } option:
If you want to allow dangling underscores in identifiers, then you can safely turn this rule off.
Source: http://eslint.org/docs/rules/
disallow dangling underscores in identifiers (no-underscore-dangle)
As far as naming conventions for identifiers go, dangling underscores may be the most polarizing in JavaScript. Dangling underscores are underscores at either the beginning or end of an identifier, such as:
var _foo;
There is actually a long history of using dangling underscores to indicate "private" members of objects in JavaScript (though JavaScript doesn't have truly private members, this convention served as a warning). This began with SpiderMonkey adding nonstandard methods such as __defineGetter__(). The intent with the underscores was to make it obvious that this method was special in some way. Since that time, using a single underscore prefix has become popular as a way to indicate "private" members of objects.
Whether or not you choose to allow dangling underscores in identifiers is purely a convention and has no effect on performance, readability, or complexity. It's purely a preference.
Rule Details
This rule disallows dangling underscores in identifiers.
Examples of incorrect code for this rule:
/*eslint no-underscore-dangle: "error"*/
var foo_;
var __proto__ ={};
foo._bar();
Examples of correct code for this rule:
/*eslint no-underscore-dangle: "error"*/
var _ =require('underscore');
var obj = _.contains(items, item);
obj.__proto__ ={};
var file = __filename;
Options
This rule has an object option:
"allow" allows specified identifiers to have dangling underscores
"allowAfterThis": false (default) disallows dangling underscores in members of the this object
"allowAfterSuper": false (default) disallows dangling underscores in members of the super object
allow
Examples of additional correct code for this rule with the { "allow": ["foo_", "_bar"] } option:
If you want to allow dangling underscores in identifiers, then you can safely turn this rule off.
Source: http://eslint.org/docs/rules/
Disallow Early Use (no-use-before-define)
In JavaScript, prior to ES6, variable and function declarations are hoisted to the top of a scope, so it's possible to use identifiers before their formal declarations in code. This can be confusing and some believe it is best to always declare variables and functions before using them.
In ES6, block-level bindings (let and const) introduce a "temporal dead zone" where a ReferenceError will be thrown with any attempt to access the variable before its declaration.
Rule Details
This rule will warn when it encounters a reference to an identifier that has not yet been declared.
functions (boolean) -
The flag which shows whether or not this rule checks function declarations.
If this is true, this rule warns every reference to a function before the function declaration.
Otherwise, ignores those references.
Function declarations are hoisted, so it's safe.
Default is true.
classes (boolean) -
The flag which shows whether or not this rule checks class declarations of upper scopes.
If this is true, this rule warns every reference to a class before the class declaration.
Otherwise, ignores those references if the declaration is in upper function scopes.
Class declarations are not hoisted, so it might be danger.
Default is true.
variables (boolean) -
This flag determines whether or not the rule checks variable declarations in upper scopes.
If this is true, the rule warns every reference to a variable before the variable declaration.
Otherwise, the rule ignores a reference if the declaration is in an upper scope, while still reporting the reference if it's in the same scope as the declaration.
Default is true.
This rule accepts "nofunc" string as an option.
"nofunc" is the same as { "functions": false, "classes": true }.
functions
Examples of correct code for the { "functions": false } option:
Disallow or enforce spaces inside of parentheses (space-in-parens)
Some style guides require or disallow spaces inside of parentheses:
foo('bar');
var x =(1+2)*3;
foo('bar');
var x =(1+2)*3;
Rule Details
This rule will enforce consistency of spacing directly inside of parentheses, by disallowing or requiring one or more spaces to the right of ( and to the left of ). In either case, () will still be allowed.
Options
There are two options for this rule:
"never" (default) enforces zero spaces inside of parentheses
"always" enforces a space inside of parentheses
Depending on your coding conventions, you can choose either option by specifying it in your configuration:
"space-in-parens": ["error", "always"]
"never"
Examples of incorrect code for this rule with the default "never" option:
/*eslint space-in-parens: ["error", "never"]*/
foo('bar');
foo('bar');
foo('bar');
var foo =(1+2)*3;
(function(){return'bar';}());
Examples of correct code for this rule with the default "never" option:
/*eslint space-in-parens: ["error", "never"]*/
foo();
foo('bar');
var foo =(1+2)*3;
(function(){return'bar';}());
"always"
Examples of incorrect code for this rule with the "always" option:
/*eslint space-in-parens: ["error", "always"]*/
foo('bar');
foo('bar');
foo('bar');
var foo =(1+2)*3;
(function(){return'bar';}());
Examples of correct code for this rule with the "always" option:
/*eslint space-in-parens: ["error", "always"]*/
foo();
foo('bar');
var foo =(1+2)*3;
(function(){return'bar';}());
Exceptions
An object literal may be used as a third array item to specify exceptions, with the key "exceptions" and an array as the value. These exceptions work in the context of the first option. That is, if "always" is set to enforce spacing, then any "exception" will disallow spacing. Conversely, if "never" is set to disallow spacing, then any "exception" will enforce spacing.
The following exceptions are available: ["{}", "[]", "()", "empty"].
Examples of incorrect code for this rule with the "never", { "exceptions": ["{}"] } option:
ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let
and const keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes
such as:
var count = people.length;
var enoughFood = count > sandwiches.length;
if(enoughFood){
var count = sandwiches.length;// accidentally overriding the count variable
console.log("We have "+ count +" sandwiches for everyone. Plenty for all!");
}
// our count variable is no longer accurate
console.log("We have "+ count +" people and "+ sandwiches.length +" sandwiches!");
Rule Details
This rule is aimed at discouraging the use of var and encouraging the use of const or let instead.
Examples
Examples of incorrect code for this rule:
/*eslint no-var: "error"*/
var x ="y";
varCONFIG={};
Examples of correct code for this rule:
/*eslint no-var: "error"*/
/*eslint-env es6*/
let x ="y";
constCONFIG={};
When Not To Use It
In addition to non-ES6 environments, existing JavaScript projects that are beginning to introduce ES6 into their
codebase may not want to apply this rule if the cost of migrating from var to let is too costly.
Source: http://eslint.org/docs/rules/
enforce consistent spacing between keys and values in object literal properties (key-spacing)
This rule enforces spacing around the colon in object literal properties. It can verify each property individually, or it can ensure horizontal alignment of adjacent properties in an object literal.
Rule Details
This rule enforces consistent spacing between keys and values in object literal properties. In the case of long lines, it is acceptable to add a new line wherever whitespace is allowed.
Options
This rule has an object option:
"beforeColon": false (default) disallows spaces between the key and the colon in object literals.
"beforeColon": true requires at least one space between the key and the colon in object literals.
"afterColon": true (default) requires at least one space between the colon and the value in object literals.
"afterColon": false disallows spaces between the colon and the value in object literals.
"mode": "strict" (default) enforces exactly one space before or after colons in object literals.
"mode": "minimum" enforces one or more spaces before or after colons in object literals.
"align": "value" enforces horizontal alignment of values in object literals.
"align": "colon" enforces horizontal alignment of both colons and values in object literals.
"align" with an object value allows for fine-grained spacing when values are being aligned in object literals.
"singleLine" specifies a spacing style for single-line object literals.
"multiLine" specifies a spacing style for multi-line object literals.
Please note that you can either use the top-level options or the grouped options (singleLine and multiLine) but not both.
beforeColon
Examples of incorrect code for this rule with the default { "beforeColon": false } option:
The align option can take additional configuration through the beforeColon, afterColon, mode, and on options.
If align is defined as an object, but not all of the parameters are provided, undefined parameters will default to the following:
// Defaults
align:{
"beforeColon":false,
"afterColon":true,
"on":"colon",
"mode":"strict"
}
Examples of correct code for this rule with sample { "align": { } } options:
/*eslint key-spacing: ["error", {
"align": {
"beforeColon": true,
"afterColon": true,
"on": "colon"
}
}]*/
var obj ={
"one":1,
"seven":7
}
/*eslint key-spacing: ["error", {
"align": {
"beforeColon": false,
"afterColon": false,
"on": "value"
}
}]*/
var obj ={
"one":1,
"seven":7
}
align and multiLine
The multiLine and align options can differ, which allows for fine-tuned control over the key-spacing of your files. align will not inherit from multiLine if align is configured as an object.
multiLine is used any time an object literal spans multiple lines. The align configuration is used when there is a group of properties in the same object. For example:
var myObj ={
key1:1,// uses multiLine
key2:2,// uses align (when defined)
key3:3,// uses align (when defined)
key4:4// uses multiLine
}
Examples of incorrect code for this rule with sample { "align": { }, "multiLine": { } } options:
/*eslint key-spacing: ["error", {
"multiLine": {
"beforeColon": false,
"afterColon":true
},
"align": {
"beforeColon": true,
"afterColon": true,
"on": "colon"
}
}]*/
var obj ={
"myObjectFunction":function(){
// Do something
},
"one":1,
"seven":7
}
Examples of correct code for this rule with sample { "align": { }, "multiLine": { } } options:
/*eslint key-spacing: ["error", {
"multiLine": {
"beforeColon": false,
"afterColon": true
},
"align": {
"beforeColon": true,
"afterColon": true,
"on": "colon"
}
}]*/
var obj ={
"myObjectFunction":function(){
// Do something
//
},// These are two separate groups, so no alignment between `myObjectFuction` and `one`
"one":1,
"seven":7// `one` and `seven` are in their own group, and therefore aligned
}
singleLine and multiLine
Examples of correct code for this rule with sample { "singleLine": { }, "multiLine": { } } options:
/*eslint "key-spacing": [2, {
"singleLine": {
"beforeColon": false,
"afterColon": true
},
"multiLine": {
"beforeColon": true,
"afterColon": true,
"align": "colon"
}
}]*/
var obj ={one:1,"two":2,three:3};
var obj2 ={
"two":2,
three:3
};
When Not To Use It
If you have another convention for property spacing that might not be consistent with the available options, or if you want to permit multiple styles concurrently you can safely disable this rule.
Source: http://eslint.org/docs/rules/
require let or const instead of var (no-var)
ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let
and const keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes
such as:
var count = people.length;
var enoughFood = count > sandwiches.length;
if(enoughFood){
var count = sandwiches.length;// accidentally overriding the count variable
console.log("We have "+ count +" sandwiches for everyone. Plenty for all!");
}
// our count variable is no longer accurate
console.log("We have "+ count +" people and "+ sandwiches.length +" sandwiches!");
Rule Details
This rule is aimed at discouraging the use of var and encouraging the use of const or let instead.
Examples
Examples of incorrect code for this rule:
/*eslint no-var: "error"*/
var x ="y";
varCONFIG={};
Examples of correct code for this rule:
/*eslint no-var: "error"*/
/*eslint-env es6*/
let x ="y";
constCONFIG={};
When Not To Use It
In addition to non-ES6 environments, existing JavaScript projects that are beginning to introduce ES6 into their
codebase may not want to apply this rule if the cost of migrating from var to let is too costly.
Source: http://eslint.org/docs/rules/
enforce consistent indentation (indent)
There are several common guidelines which require specific indentation of nested blocks and statements, like:
functionhello(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;
functionfoo(d){
e=f;
}
}
Examples of correct code for this rule with the default options:
/*eslint indent: "error"*/
if(a){
b=c;
functionfoo(d){
e=f;
}
}
This rule has an object option:
"SwitchCase" (default: 0) enforces indentation level for case clauses in switch statements
"VariableDeclarator" (default: 1) enforces indentation level for var declarators; can also take an object to define separate rules for var, let and const 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 to 2 will indent the multi-line variable declarations with 8 spaces.
Indent of 2 spaces with VariableDeclarator set to 2 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 for var and let, 6 spaces for const statements.
Indent of tab with VariableDeclarator set to 2 will indent the multi-line variable declarations with 2 tabs.
Indent of 2 spaces with SwitchCase set to 0 will not indent case clauses with respect to switch statements.
Indent of 2 spaces with SwitchCase set to 1 will indent case clauses with 2 spaces with respect to switch statements.
Indent of 2 spaces with SwitchCase set to 2 will indent case clauses with 4 spaces with respect to switch statements.
Indent of tab with SwitchCase set to 2 will indent case clauses with 2 tabs with respect to switch statements.
Indent of 2 spaces with MemberExpression set to 0 will indent the multi-line property chains with 0 spaces.
Indent of 2 spaces with MemberExpression set to 1 will indent the multi-line property chains with 2 spaces.
Indent of 2 spaces with MemberExpression set to 2 will indent the multi-line property chains with 4 spaces.
Indent of 4 spaces with MemberExpression set to 0 will indent the multi-line property chains with 0 spaces.
Indent of 4 spaces with MemberExpression set to 1 will indent the multi-line property chains with 4 spaces.
Indent of 4 spaces with MemberExpression set to 2 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;
functionfoo(d){
e=f;
}
}
Examples of correct code for this rule with the "tab" option:
/*eslint indent: ["error", "tab"]*/
if(a){
/*tab*/b=c;
/*tab*/functionfoo(d){
/*tab*//*tab*/e=f;
/*tab*/}
}
SwitchCase
Examples of incorrect code for this rule with the 2, { "SwitchCase": 1 } options:
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:
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.
Require Variable Declarations to be at the top of their scope (vars-on-top)
The vars-on-top rule generates warnings when variable declarations are not used serially at the top of a function scope or the top of a program.
By default variable declarations are always moved (“hoisted”) invisibly to the top of their containing scope by the JavaScript interpreter.
This rule forces the programmer to represent that behaviour by manually moving the variable declaration to the top of its containing scope.
Rule Details
This rule aims to keep all variable declarations in the leading series of statements.
Allowing multiple declarations helps promote maintainability and is thus allowed.
Examples of incorrect code for this rule:
/*eslint vars-on-top: "error"*/
// Variable declarations in a block:
functiondoSomething(){
var first;
if(true){
first =true;
}
var second;
}
// Variable declaration in for initializer:
functiondoSomething(){
for(var i=0; i<10; i++){}
}
/*eslint vars-on-top: "error"*/
// Variables after other statements:
f();
var a;
Examples of correct code for this rule:
/*eslint vars-on-top: "error"*/
functiondoSomething(){
var first;
var second;//multiple declarations are allowed at the top