In JavaScript, it's possible to redeclare the same variable name using var. This can lead to confusion as to where the variable is actually declared and initialized.
Rule Details
This rule is aimed at eliminating variables that have multiple declarations in the same scope.
Examples of incorrect code for this rule:
/*eslint no-redeclare: "error"*/
var a =3;
var a =10;
Examples of correct code for this rule:
/*eslint no-redeclare: "error"*/
var a =3;
// ...
a =10;
Options
This rule takes one optional argument, an object with a boolean property "builtinGlobals". It defaults to false.
If set to true, this rule also checks redeclaration of built-in globals, such as Object, Array, Number...
builtinGlobals
Examples of incorrect code for the { "builtinGlobals": true } option:
The browser environment has many built-in global variables (for example, top). Some of built-in global variables cannot be redeclared.
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 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
Require or disallow named function expressions (func-names)
A pattern that's becoming more common is to give function expressions names to aid in debugging. For example:
Foo.prototype.bar=functionbar(){};
Adding the second bar in the above example is optional. If you leave off the function name then when the function throws an exception you are likely to get something similar to anonymous function in the stack trace. If you provide the optional name for a function expression then you will get the name of the function expression in the stack trace.
Rule Details
This rule can enforce or disallow the use of named function expressions.
Options
This rule has a string option:
"always" (default) requires function expressions to have a name
"as-needed" requires function expressions to have a name, if the name cannot be assigned automatically in an ES6 environment
"never" disallows named function expressions, except in recursive functions, where a name is needed
always
Examples of incorrect code for this rule with the default "always" option:
/*eslint func-names: ["error", "always"]*/
Foo.prototype.bar=function(){};
(function(){
// ...
}())
Examples of correct code for this rule with the default "always" option:
/*eslint func-names: ["error", "always"]*/
Foo.prototype.bar=functionbar(){};
(functionbar(){
// ...
}())
as-needed
ECMAScript 6 introduced a name property on all functions. The value of name is determined by evaluating the code around the function to see if a name can be inferred. For example, a function assigned to a variable will automatically have a name property equal to the name of the variable. The value of name is then used in stack traces for easier debugging.
Examples of incorrect code for this rule with the default "as-needed" option:
/*eslint func-names: ["error", "as-needed"]*/
Foo.prototype.bar=function(){};
(function(){
// ...
}())
Examples of correct code for this rule with the default "as-needed" option:
/*eslint func-names: ["error", "as-needed"]*/
varbar=function(){};
(functionbar(){
// ...
}())
never
Examples of incorrect code for this rule with the "never" option:
/*eslint func-names: ["error", "never"]*/
Foo.prototype.bar=functionbar(){};
(functionbar(){
// ...
}())
Examples of correct code for this rule with the "never" option:
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:
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/
Disallow Unused Variables (no-unused-vars)
Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers.
Rule Details
This rule is aimed at eliminating unused variables, functions, and parameters of functions.
A variable is considered to be used if any of the following are true:
It represents a function that is called (doSomething())
It is read (var y = x)
It is passed into a function as an argument (doSomething(x))
It is read inside of a function that is passed to another function (doSomething(function() { foo(); }))
A variable is not considered to be used if it is only ever assigned to (var x = 5) or declared.
Examples of incorrect code for this rule:
/*eslint no-unused-vars: "error"*/
/*global some_unused_var*/
// It checks variables you have defined as global
some_unused_var =42;
var x;
// Write-only variables are not considered as used.
var y =10;
y =5;
// A read for a modification of itself is not considered as used.
var z =0;
z = z +1;
// By default, unused arguments cause warnings.
(function(foo){
return5;
})();
// Unused recursive functions also cause warnings.
functionfact(n){
if(n <2)return1;
return n *fact(n -1);
}
// When a function definition destructures an array, unused entries from the array also cause warnings.
functiongetY([x, y]){
return y;
}
Examples of correct code for this rule:
/*eslint no-unused-vars: "error"*/
var x =10;
alert(x);
// foo is considered used here
myFunc(functionfoo(){
// ...
}.bind(this));
(function(foo){
return foo;
})();
var myFunc;
myFunc =setTimeout(function(){
// myFunc is considered used
myFunc();
},50);
// Only the second argument from the descructured array is used.
functiongetY([, y]){
return y;
}
exported
In environments outside of CommonJS or ECMAScript modules, you may use var to create a global variable that may be used by other scripts. You can use the /* exported variableName */ comment block to indicate that this variable is being exported and therefore should not be considered unused.
Note that /* exported */ has no effect for any of the following:
when the environment is node or commonjs
when parserOptions.sourceType is module
when ecmaFeatures.globalReturn is true
The line comment // exported variableName will not work as exported is not line-specific.
Examples of correct code for /* exported variableName */ operation:
/* exported global_var */
var global_var =42;
Options
This rule takes one argument which can be a string or an object. The string settings are the same as those of the vars property (explained below).
By default this rule is enabled with all option for variables and after-used for arguments.
The varsIgnorePattern option specifies exceptions not to check for usage: variables whose names match a regexp pattern. For example, variables whose names contain ignored or Ignored.
Examples of correct code for the { "varsIgnorePattern": "[iI]gnored" } option:
after-used - only the last argument must be used. This allows you, for instance, to have two named parameters to a function and as long as you use the second argument, ESLint will not warn you about the first. This is the default setting.
all - all named arguments must be used.
none - do not check arguments.
args: after-used
Examples of incorrect code for the default { "args": "after-used" } option:
The ignoreRestSiblings option is a boolean (default: false). Using a Rest Property it is possible to "omit" properties from an object, but by default the sibling properties are marked as "unused". With this option enabled the rest property's siblings are ignored.
Examples of correct code for the { "ignoreRestSiblings": true } option:
// 'type' is ignored because it has a rest property sibling.
var{ type,...coords }= data;
argsIgnorePattern
The argsIgnorePattern option specifies exceptions not to check for usage: arguments whose names match a regexp pattern. For example, variables whose names begin with an underscore.
Examples of correct code for the { "argsIgnorePattern": "^_" } option:
The caughtErrorsIgnorePattern option specifies exceptions not to check for usage: catch arguments whose names match a regexp pattern. For example, variables whose names begin with a string 'ignore'.
Examples of correct code for the { "caughtErrorsIgnorePattern": "^ignore" } option:
If you don't want to be notified about unused variables or function arguments, you can safely turn this rule off.
Source: http://eslint.org/docs/rules/
Treat var as Block Scoped (block-scoped-var)
The block-scoped-var rule generates warnings when variables are used outside of the block in which they were defined. This emulates C-style block scope.
Rule Details
This rule aims to reduce the usage of variables outside of their binding context and emulate traditional block scope from other languages. This is to help newcomers to the language avoid difficult bugs with variable hoisting.
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.
In JavaScript, it's possible to redeclare the same variable name using var. This can lead to confusion as to where the variable is actually declared and initialized.
Rule Details
This rule is aimed at eliminating variables that have multiple declarations in the same scope.
Examples of incorrect code for this rule:
/*eslint no-redeclare: "error"*/
var a =3;
var a =10;
Examples of correct code for this rule:
/*eslint no-redeclare: "error"*/
var a =3;
// ...
a =10;
Options
This rule takes one optional argument, an object with a boolean property "builtinGlobals". It defaults to false.
If set to true, this rule also checks redeclaration of built-in globals, such as Object, Array, Number...
builtinGlobals
Examples of incorrect code for the { "builtinGlobals": true } option:
The browser environment has many built-in global variables (for example, top). Some of built-in global variables cannot be redeclared.
Source: http://eslint.org/docs/rules/
require or disallow assignment operator shorthand where possible (operator-assignment)
JavaScript provides shorthand operators that combine variable assignment and some simple mathematical operations. For example, x = x + 4 can be shortened to x += 4. The supported shorthand forms are as follows:
Shorthand | Separate
-----------|------------
x += y | x = x + y
x -= y | x = x - y
x *= y | x = x * y
x /= y | x = x / y
x %= y | x = x % y
x <<= y | x = x << y
x >>= y | x = x >> y
x >>>= y | x = x >>> y
x &= y | x = x & y
x ^= y | x = x ^ y
x |= y | x = x | y
Rule Details
This rule requires or disallows assignment operator shorthand where possible.
Options
This rule has a single string option:
"always" (default) requires assignment operator shorthand where possible
"never" disallows assignment operator shorthand
always
Examples of incorrect code for this rule with the default "always" option:
Use of operator assignment shorthand is a stylistic choice. Leaving this rule turned off would allow developers to choose which style is more readable on a case-by-case basis.
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/
Suggest using template literals instead of string concatenation. (prefer-template)
In ES2015 (ES6), we can use template literals instead of string concatenation.
var str ="Hello, "+ name +"!";
/*eslint-env es6*/
var str =`Hello, ${name}!`;
Rule Details
This rule is aimed to flag usage of + operators with strings.
Examples
Examples of incorrect code for this rule:
/*eslint prefer-template: "error"*/
var str ="Hello, "+ name +"!";
var str ="Time: "+(12*60*60*1000);
Examples of correct code for this rule:
/*eslint prefer-template: "error"*/
/*eslint-env es6*/
var str ="Hello World!";
var str =`Hello, ${name}!`;
var str =`Time: ${12*60*60*1000}`;
// This is reported by `no-useless-concat`.
var str ="Hello, "+"World!";
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 string concatenation, you can safely disable this rule.
Spacing around commas improve readability of a list of items. Although most of the style guidelines for languages prescribe adding a space after a comma and not before it, it is subjective to the preferences of a project.
var foo =1, bar =2;
var foo =1,bar =2;
Rule Details
This rule enforces consistent spacing before and after commas in variable declarations, array literals, object literals, function parameters, and sequences.
This rule does not apply in an ArrayExpression or ArrayPattern in either of the following cases:
adjacent null elements
an initial null element, to avoid conflicts with the [array-bracket-spacing](array-bracket-spacing.md) rule
Options
This rule has an object option:
"before": false (default) disallows spaces before commas
"before": true requires one or more spaces before commas
"after": true (default) requires one or more spaces after commas
"after": false disallows spaces after commas
after
Examples of incorrect code for this rule with the default { "before": false, "after": true } options:
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
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){}
The --fix option on the command line automatically fixes some problems reported by this rule. A problem is only fixed if one of the operands is a typeof expression, or if both operands are literals with the same type.
Options
always
The "always" option (default) enforces the use of === and !== in every situation (except when you opt-in to more specific handling of null [see below]).
Examples of incorrect code for the "always" option:
/*eslint eqeqeq: ["error", "always"]*/
a == b
foo ==true
bananas !=1
value ==undefined
typeof foo =='undefined'
'hello'!='world'
0==0
true==true
foo ==null
Examples of correct code for the "always" option:
/*eslint eqeqeq: ["error", "always"]*/
a === b
foo ===true
bananas !==1
value ===undefined
typeof foo ==='undefined'
'hello'!=='world'
0===0
true===true
foo ===null
This rule optionally takes a second argument, which should be an object with the following supported properties:
"null": Customize how this rule treats null literals. Possible values:
always (default) - Always use === or !==.
never - Never use === or !== with null.
ignore - Do not apply this rule to null.
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
Deprecated: Instead of using this option use "always" and pass a "null" option property with value "ignore". This will tell eslint to always enforce strict equality except when comparing with the null literal.
["error","always",{"null":"ignore"}]
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/
Require Camelcase (camelcase)
When it comes to naming variables, style guides generally fall into one of two camps: camelcase (variableName) and underscores (variable_name). This rule focuses on using the camelcase approach. If your style guide calls for camelcasing your variable names, then this rule is for you!
Rule Details
This rule looks for any underscores (_) located within the source code. It ignores leading and trailing underscores and only checks those in the middle of a variable name. If ESLint decides that the variable is a constant (all uppercase), then no warning will be thrown. Otherwise, a warning will be thrown. This rule only flags definitions and assignments but not function calls. In case of ES6 import statements, this rule only targets the name of the variable that will be imported into the local module scope.
Options
This rule has an object option:
"properties": "always" (default) enforces camelcase style for property names
"properties": "never" does not check property names
always
Examples of incorrect code for this rule with the default { "properties": "always" } option:
/*eslint camelcase: "error"*/
import{ no_camelcased }from"external-module"
var my_favorite_color ="#112C85";
functiondo_something(){
// ...
}
obj.do_something=function(){
// ...
};
var obj ={
my_pref:1
};
Examples of correct code for this rule with the default { "properties": "always" } option:
/*eslint camelcase: "error"*/
import{ no_camelcased as camelCased }from"external-module";
var myFavoriteColor ="#112C85";
var _myFavoriteColor ="#112C85";
var myFavoriteColor_ ="#112C85";
varMY_FAVORITE_COLOR="#112C85";
var foo = bar.baz_boom;
var foo ={qux: bar.baz_boom };
obj.do_something();
do_something();
newdo_something();
var{category_id: category }= query;
never
Examples of correct code for this rule with the { "properties": "never" } option:
If you have established coding standards using a different naming convention (separating words with underscores), 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.
Spacing around commas improve readability of a list of items. Although most of the style guidelines for languages prescribe adding a space after a comma and not before it, it is subjective to the preferences of a project.
var foo =1, bar =2;
var foo =1,bar =2;
Rule Details
This rule enforces consistent spacing before and after commas in variable declarations, array literals, object literals, function parameters, and sequences.
This rule does not apply in an ArrayExpression or ArrayPattern in either of the following cases:
adjacent null elements
an initial null element, to avoid conflicts with the [array-bracket-spacing](array-bracket-spacing.md) rule
Options
This rule has an object option:
"before": false (default) disallows spaces before commas
"before": true requires one or more spaces before commas
"after": true (default) requires one or more spaces after commas
"after": false disallows spaces after commas
after
Examples of incorrect code for this rule with the default { "before": false, "after": true } options:
enforce the consistent use of either backticks, double, or single quotes (quotes)
JavaScript allows you to define strings in one of three ways: double quotes, single quotes, and backticks (as of ECMAScript 6). For example:
/*eslint-env es6*/
var double ="double";
var single ='single';
var backtick =`backtick`;// ES6 only
Each of these lines creates a string and, in some cases, can be used interchangeably. The choice of how to define strings in a codebase is a stylistic one outside of template literals (which allow embedded of expressions to be interpreted).
Many codebases require strings to be defined in a consistent manner.
Rule Details
This rule enforces the consistent use of either backticks, double, or single quotes.
Options
This rule has two options, a string option and an object option.
String option:
"double" (default) requires the use of double quotes wherever possible
"single" requires the use of single quotes wherever possible
"backtick" requires the use of backticks wherever possible
Object option:
"avoidEscape": true allows strings to use single-quotes or double-quotes so long as the string contains a quote that would have to be escaped otherwise
"allowTemplateLiterals": true allows strings to use backticks
Deprecated: The object property avoid-escape is deprecated; please use the object property avoidEscape instead.
double
Examples of incorrect code for this rule with the default "double" option:
/*eslint quotes: ["error", "double"]*/
var single ='single';
var unescaped ='a string containing "double" quotes';
Examples of correct code for this rule with the default "double" option:
/*eslint quotes: ["error", "double"]*/
/*eslint-env es6*/
var double ="double";
var backtick =`back\ntick`;// backticks are allowed due to newline
var backtick = tag`backtick`;// backticks are allowed due to tag
single
Examples of incorrect code for this rule with the "single" option:
/*eslint quotes: ["error", "single"]*/
var double ="double";
var unescaped ="a string containing 'single' quotes";
Examples of correct code for this rule with the "single" option:
/*eslint quotes: ["error", "single"]*/
/*eslint-env es6*/
var single ='single';
var backtick =`back${x}tick`;// backticks are allowed due to substitution
backticks
Examples of incorrect code for this rule with the "backtick" option:
/*eslint quotes: ["error", "backtick"]*/
var single ='single';
var double ="double";
var unescaped ='a string containing `backticks`';
Examples of correct code for this rule with the "backtick" option:
/*eslint quotes: ["error", "backtick"]*/
/*eslint-env es6*/
var backtick =`backtick`;
avoidEscape
Examples of additional correct code for this rule with the "double", { "avoidEscape": true } options: