Function validateClicked
has 5 arguments (exceeds 4 allowed). Consider refactoring. Open
this.validateClicked = function($event, authType, formSubmit, angularForm, url) {
- Create a ticketCreate a ticket
Unexpected string concatenation. Open
url += '&attributes=' + options.attributes.map(encodeURIComponent).join(',');
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
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.
Related Rules
- [no-useless-concat](no-useless-concat.md)
- [quotes](quotes.md) Source: http://eslint.org/docs/rules/
Unexpected function expression. Open
.then(function(response) {
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Require using arrow functions for callbacks (prefer-arrow-callback)
Arrow functions can be an attractive alternative to function expressions for callbacks or function arguments.
For example, arrow functions are automatically bound to their surrounding scope/context. This provides an alternative to the pre-ES6 standard of explicitly binding function expressions to achieve similar behavior.
Additionally, arrow functions are:
less verbose, and easier to reason about.
bound lexically regardless of where or when they are invoked.
Rule Details
This rule locates function expressions used as callbacks or function arguments. An error will be produced for any that could be replaced by an arrow function without changing the result.
The following examples will be flagged:
/* eslint prefer-arrow-callback: "error" */
foo(function(a) { return a; }); // ERROR
// prefer: foo(a => a)
foo(function() { return this.a; }.bind(this)); // ERROR
// prefer: foo(() => this.a)
Instances where an arrow function would not produce identical results will be ignored.
The following examples will not be flagged:
/* eslint prefer-arrow-callback: "error" */
/* eslint-env es6 */
// arrow function callback
foo(a => a); // OK
// generator as callback
foo(function*() { yield; }); // OK
// function expression not used as callback or function argument
var foo = function foo(a) { return a; }; // OK
// unbound function expression callback
foo(function() { return this.a; }); // OK
// recursive named function callback
foo(function bar(n) { return n && n + bar(n - 1); }); // OK
Options
Access further control over this rule's behavior via an options object.
Default: { allowNamedFunctions: false, allowUnboundThis: true }
allowNamedFunctions
By default { "allowNamedFunctions": false }
, this boolean
option prohibits using named functions as callbacks or function arguments.
Changing this value to true
will reverse this option's behavior by allowing use of named functions without restriction.
{ "allowNamedFunctions": true }
will not flag the following example:
/* eslint prefer-arrow-callback: [ "error", { "allowNamedFunctions": true } ] */
foo(function bar() {});
allowUnboundThis
By default { "allowUnboundThis": true }
, this boolean
option allows function expressions containing this
to be used as callbacks, as long as the function in question has not been explicitly bound.
When set to false
this option prohibits the use of function expressions as callbacks or function arguments entirely, without exception.
{ "allowUnboundThis": false }
will flag the following examples:
/* 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
In environments that have not yet adopted ES6 language features (ES3/5).
In ES6+ environments that allow the use of function expressions when describing callbacks or function arguments.
Further Reading
Unexpected var, use let or const instead. Open
for (var k in serializedObj) {
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
require let
or const
instead of var
(no-var)
ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let
and const
keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes
such as:
var count = people.length;
var enoughFood = count > sandwiches.length;
if (enoughFood) {
var count = sandwiches.length; // accidentally overriding the count variable
console.log("We have " + count + " sandwiches for everyone. Plenty for all!");
}
// our count variable is no longer accurate
console.log("We have " + count + " people and " + sandwiches.length + " sandwiches!");
Rule Details
This rule is aimed at discouraging the use of var
and encouraging the use of const
or let
instead.
Examples
Examples of incorrect code for this rule:
/*eslint no-var: "error"*/
var x = "y";
var CONFIG = {};
Examples of correct code for this rule:
/*eslint no-var: "error"*/
/*eslint-env es6*/
let x = "y";
const CONFIG = {};
When Not To Use It
In addition to non-ES6 environments, existing JavaScript projects that are beginning to introduce ES6 into their
codebase may not want to apply this rule if the cost of migrating from var
to let
is too costly.
Source: http://eslint.org/docs/rules/
Expected property shorthand. Open
miqFlashLater({message: message, level: flashType});
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Require Object Literal Shorthand Syntax (object-shorthand)
ECMAScript 6 provides a concise form for defining object literal methods and properties. This syntax can make defining complex object literals much cleaner.
Here are a few common examples using the ES5 syntax:
// properties
var foo = {
x: x,
y: y,
z: z,
};
// methods
var foo = {
a: function() {},
b: function() {}
};
Now here are ES6 equivalents:
/*eslint-env es6*/
// properties
var foo = {x, y, z};
// methods
var foo = {
a() {},
b() {}
};
Rule Details
This rule enforces the use of the shorthand syntax. This applies to all methods (including generators) defined in object literals and any properties defined where the key name matches name of the assigned variable.
Each of the following properties would warn:
/*eslint object-shorthand: "error"*/
/*eslint-env es6*/
var foo = {
w: function() {},
x: function *() {},
[y]: function() {},
z: z
};
In that case the expected syntax would have been:
/*eslint object-shorthand: "error"*/
/*eslint-env es6*/
var foo = {
w() {},
*x() {},
[y]() {},
z
};
This rule does not flag arrow functions inside of object literals. The following will not warn:
/*eslint object-shorthand: "error"*/
/*eslint-env es6*/
var foo = {
x: (y) => y
};
See Also:
-
no-useless-rename
which disallows renaming import, export, and destructured assignments to the same name.
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 long-form will be used in an object literal. -
"consistent-as-needed"
ensures that either all shorthand or all long-form 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 long-form syntax is preferred whenever the object key is a string literal (default:false
). Note that this option can only be enabled when the string option is set to"always"
,"methods"
, or"properties"
. -
"ignoreConstructors": true
can be used to prevent the rule from reporting errors for constructor functions. (By default, the rule treats constructors the same way as other functions.) Note that this option can only be enabled when the string option is set to"always"
or"methods"
. -
"avoidExplicitReturnArrows": true
indicates that methods are preferred over explicit-return arrow functions for function properties. (By default, the rule allows either of these.) Note that this option can only be enabled when the string option is set to"always"
or"methods"
.
avoidQuotes
{
"object-shorthand": ["error", "always", { "avoidQuotes": true }]
}
Example of incorrect code for this rule with the "always", { "avoidQuotes": true }
option:
/*eslint object-shorthand: ["error", "always", { "avoidQuotes": true }]*/
/*eslint-env es6*/
var foo = {
"bar-baz"() {}
};
Example of correct code for this rule with the "always", { "avoidQuotes": true }
option:
/*eslint object-shorthand: ["error", "always", { "avoidQuotes": true }]*/
/*eslint-env es6*/
var foo = {
"bar-baz": function() {},
"qux": qux
};
ignoreConstructors
{
"object-shorthand": ["error", "always", { "ignoreConstructors": true }]
}
Example of correct code for this rule with the "always", { "ignoreConstructors": true }
option:
/*eslint object-shorthand: ["error", "always", { "ignoreConstructors": true }]*/
/*eslint-env es6*/
var foo = {
ConstructorFunction: function() {}
};
avoidExplicitReturnArrows
{
"object-shorthand": ["error", "always", { "avoidExplicitReturnArrows": true }]
}
Example of incorrect code for this rule with the "always", { "avoidExplicitReturnArrows": true }
option:
/*eslint object-shorthand: ["error", "always", { "avoidExplicitReturnArrows": true }]*/
/*eslint-env es6*/
var foo = {
foo: (bar, baz) => {
return bar + baz;
},
qux: (foobar) => {
return foobar * 2;
}
};
Example of correct code for this rule with the "always", { "avoidExplicitReturnArrows": true }
option:
/*eslint object-shorthand: ["error", "always", { "avoidExplicitReturnArrows": true }]*/
/*eslint-env es6*/
var foo = {
foo(bar, baz) {
return bar + baz;
},
qux: foobar => foobar * 2
};
Example of incorrect code for this rule with the "consistent"
option:
/*eslint object-shorthand: [2, "consistent"]*/
/*eslint-env es6*/
var foo = {
a,
b: "foo",
};
Examples of correct code for this rule with the "consistent"
option:
/*eslint object-shorthand: [2, "consistent"]*/
/*eslint-env es6*/
var foo = {
a: a,
b: "foo"
};
var bar = {
a,
b,
};
Example of incorrect code with the "consistent-as-needed"
option, which is very similar to "consistent"
:
/*eslint object-shorthand: [2, "consistent-as-needed"]*/
/*eslint-env es6*/
var foo = {
a: a,
b: b,
};
When Not To Use It
Anyone not yet in an ES6 environment would not want to apply this rule. Others may find the terseness of the shorthand syntax harder to read and may not want to encourage it with this rule.
Further Reading
Object initializer - MDN Source: http://eslint.org/docs/rules/
Unexpected var, use let or const instead. Open
var miqService = this;
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
require let
or const
instead of var
(no-var)
ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let
and const
keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes
such as:
var count = people.length;
var enoughFood = count > sandwiches.length;
if (enoughFood) {
var count = sandwiches.length; // accidentally overriding the count variable
console.log("We have " + count + " sandwiches for everyone. Plenty for all!");
}
// our count variable is no longer accurate
console.log("We have " + count + " people and " + sandwiches.length + " sandwiches!");
Rule Details
This rule is aimed at discouraging the use of var
and encouraging the use of const
or let
instead.
Examples
Examples of incorrect code for this rule:
/*eslint no-var: "error"*/
var x = "y";
var CONFIG = {};
Examples of correct code for this rule:
/*eslint no-var: "error"*/
/*eslint-env es6*/
let x = "y";
const CONFIG = {};
When Not To Use It
In addition to non-ES6 environments, existing JavaScript projects that are beginning to introduce ES6 into their
codebase may not want to apply this rule if the cost of migrating from var
to let
is too costly.
Source: http://eslint.org/docs/rules/
All 'var' declarations must be at the top of the function scope. Open
for (var k in serializedObj) {
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Require Variable Declarations to be at the top of their scope (vars-on-top)
The vars-on-top
rule generates warnings when variable declarations are not used serially at the top of a function scope or the top of a program.
By default variable declarations are always moved (“hoisted”) invisibly to the top of their containing scope by the JavaScript interpreter.
This rule forces the programmer to represent that behavior by manually moving the variable declaration to the top of its containing scope.
Rule Details
This rule aims to keep all variable declarations in the leading series of statements. Allowing multiple declarations helps promote maintainability and is thus allowed.
Examples of incorrect code for this rule:
/*eslint vars-on-top: "error"*/
// Variable declarations in a block:
function doSomething() {
var first;
if (true) {
first = true;
}
var second;
}
// Variable declaration in for initializer:
function doSomething() {
for (var i=0; i<10; i++) {}
}
/*eslint vars-on-top: "error"*/
// Variables after other statements:
f();
var a;
Examples of correct code for this rule:
/*eslint vars-on-top: "error"*/
function doSomething() {
var first;
var second; //multiple declarations are allowed at the top
if (true) {
first = true;
}
}
function doSomething() {
var i;
for (i=0; i<10; i++) {}
}
/*eslint vars-on-top: "error"*/
var a;
f();
/*eslint vars-on-top: "error"*/
// Directives may precede variable declarations.
"use strict";
var a;
f();
// Comments can describe variables.
function doSomething() {
// this is the first var.
var first;
// this is the second var.
var second
}
Further Reading
All 'var' declarations must be at the top of the function scope. Open
var url = '/api/providers?collection_class=ManageIQ::Providers::NetworkManager&expand=resources';
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Require Variable Declarations to be at the top of their scope (vars-on-top)
The vars-on-top
rule generates warnings when variable declarations are not used serially at the top of a function scope or the top of a program.
By default variable declarations are always moved (“hoisted”) invisibly to the top of their containing scope by the JavaScript interpreter.
This rule forces the programmer to represent that behavior by manually moving the variable declaration to the top of its containing scope.
Rule Details
This rule aims to keep all variable declarations in the leading series of statements. Allowing multiple declarations helps promote maintainability and is thus allowed.
Examples of incorrect code for this rule:
/*eslint vars-on-top: "error"*/
// Variable declarations in a block:
function doSomething() {
var first;
if (true) {
first = true;
}
var second;
}
// Variable declaration in for initializer:
function doSomething() {
for (var i=0; i<10; i++) {}
}
/*eslint vars-on-top: "error"*/
// Variables after other statements:
f();
var a;
Examples of correct code for this rule:
/*eslint vars-on-top: "error"*/
function doSomething() {
var first;
var second; //multiple declarations are allowed at the top
if (true) {
first = true;
}
}
function doSomething() {
var i;
for (i=0; i<10; i++) {}
}
/*eslint vars-on-top: "error"*/
var a;
f();
/*eslint vars-on-top: "error"*/
// Directives may precede variable declarations.
"use strict";
var a;
f();
// Comments can describe variables.
function doSomething() {
// this is the first var.
var first;
// this is the second var.
var second
}
Further Reading
Unexpected var, use let or const instead. Open
var serializedObj = angular.copy(model);
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
require let
or const
instead of var
(no-var)
ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let
and const
keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes
such as:
var count = people.length;
var enoughFood = count > sandwiches.length;
if (enoughFood) {
var count = sandwiches.length; // accidentally overriding the count variable
console.log("We have " + count + " sandwiches for everyone. Plenty for all!");
}
// our count variable is no longer accurate
console.log("We have " + count + " people and " + sandwiches.length + " sandwiches!");
Rule Details
This rule is aimed at discouraging the use of var
and encouraging the use of const
or let
instead.
Examples
Examples of incorrect code for this rule:
/*eslint no-var: "error"*/
var x = "y";
var CONFIG = {};
Examples of correct code for this rule:
/*eslint no-var: "error"*/
/*eslint-env es6*/
let x = "y";
const CONFIG = {};
When Not To Use It
In addition to non-ES6 environments, existing JavaScript projects that are beginning to introduce ES6 into their
codebase may not want to apply this rule if the cost of migrating from var
to let
is too costly.
Source: http://eslint.org/docs/rules/
All 'var' declarations must be at the top of the function scope. Open
var message = __('Unknown error');
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Require Variable Declarations to be at the top of their scope (vars-on-top)
The vars-on-top
rule generates warnings when variable declarations are not used serially at the top of a function scope or the top of a program.
By default variable declarations are always moved (“hoisted”) invisibly to the top of their containing scope by the JavaScript interpreter.
This rule forces the programmer to represent that behavior by manually moving the variable declaration to the top of its containing scope.
Rule Details
This rule aims to keep all variable declarations in the leading series of statements. Allowing multiple declarations helps promote maintainability and is thus allowed.
Examples of incorrect code for this rule:
/*eslint vars-on-top: "error"*/
// Variable declarations in a block:
function doSomething() {
var first;
if (true) {
first = true;
}
var second;
}
// Variable declaration in for initializer:
function doSomething() {
for (var i=0; i<10; i++) {}
}
/*eslint vars-on-top: "error"*/
// Variables after other statements:
f();
var a;
Examples of correct code for this rule:
/*eslint vars-on-top: "error"*/
function doSomething() {
var first;
var second; //multiple declarations are allowed at the top
if (true) {
first = true;
}
}
function doSomething() {
var i;
for (i=0; i<10; i++) {}
}
/*eslint vars-on-top: "error"*/
var a;
f();
/*eslint vars-on-top: "error"*/
// Directives may precede variable declarations.
"use strict";
var a;
f();
// Comments can describe variables.
function doSomething() {
// this is the first var.
var first;
// this is the second var.
var second
}
Further Reading
Unexpected var, use let or const instead. Open
var serializedObj = angular.copy(model);
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
require let
or const
instead of var
(no-var)
ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let
and const
keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes
such as:
var count = people.length;
var enoughFood = count > sandwiches.length;
if (enoughFood) {
var count = sandwiches.length; // accidentally overriding the count variable
console.log("We have " + count + " sandwiches for everyone. Plenty for all!");
}
// our count variable is no longer accurate
console.log("We have " + count + " people and " + sandwiches.length + " sandwiches!");
Rule Details
This rule is aimed at discouraging the use of var
and encouraging the use of const
or let
instead.
Examples
Examples of incorrect code for this rule:
/*eslint no-var: "error"*/
var x = "y";
var CONFIG = {};
Examples of correct code for this rule:
/*eslint no-var: "error"*/
/*eslint-env es6*/
let x = "y";
const CONFIG = {};
When Not To Use It
In addition to non-ES6 environments, existing JavaScript projects that are beginning to introduce ES6 into their
codebase may not want to apply this rule if the cost of migrating from var
to let
is too costly.
Source: http://eslint.org/docs/rules/
Unexpected var, use let or const instead. Open
var url = '/api/providers?collection_class=ManageIQ::Providers::NetworkManager&expand=resources';
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
require let
or const
instead of var
(no-var)
ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let
and const
keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes
such as:
var count = people.length;
var enoughFood = count > sandwiches.length;
if (enoughFood) {
var count = sandwiches.length; // accidentally overriding the count variable
console.log("We have " + count + " sandwiches for everyone. Plenty for all!");
}
// our count variable is no longer accurate
console.log("We have " + count + " people and " + sandwiches.length + " sandwiches!");
Rule Details
This rule is aimed at discouraging the use of var
and encouraging the use of const
or let
instead.
Examples
Examples of incorrect code for this rule:
/*eslint no-var: "error"*/
var x = "y";
var CONFIG = {};
Examples of correct code for this rule:
/*eslint no-var: "error"*/
/*eslint-env es6*/
let x = "y";
const CONFIG = {};
When Not To Use It
In addition to non-ES6 environments, existing JavaScript projects that are beginning to introduce ES6 into their
codebase may not want to apply this rule if the cost of migrating from var
to let
is too costly.
Source: http://eslint.org/docs/rules/
Unexpected var, use let or const instead. Open
var message = __('Unknown error');
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
require let
or const
instead of var
(no-var)
ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let
and const
keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes
such as:
var count = people.length;
var enoughFood = count > sandwiches.length;
if (enoughFood) {
var count = sandwiches.length; // accidentally overriding the count variable
console.log("We have " + count + " sandwiches for everyone. Plenty for all!");
}
// our count variable is no longer accurate
console.log("We have " + count + " people and " + sandwiches.length + " sandwiches!");
Rule Details
This rule is aimed at discouraging the use of var
and encouraging the use of const
or let
instead.
Examples
Examples of incorrect code for this rule:
/*eslint no-var: "error"*/
var x = "y";
var CONFIG = {};
Examples of correct code for this rule:
/*eslint no-var: "error"*/
/*eslint-env es6*/
let x = "y";
const CONFIG = {};
When Not To Use It
In addition to non-ES6 environments, existing JavaScript projects that are beginning to introduce ES6 into their
codebase may not want to apply this rule if the cost of migrating from var
to let
is too costly.
Source: http://eslint.org/docs/rules/
Unexpected function expression. Open
.then(function success(data) {
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Require using arrow functions for callbacks (prefer-arrow-callback)
Arrow functions can be an attractive alternative to function expressions for callbacks or function arguments.
For example, arrow functions are automatically bound to their surrounding scope/context. This provides an alternative to the pre-ES6 standard of explicitly binding function expressions to achieve similar behavior.
Additionally, arrow functions are:
less verbose, and easier to reason about.
bound lexically regardless of where or when they are invoked.
Rule Details
This rule locates function expressions used as callbacks or function arguments. An error will be produced for any that could be replaced by an arrow function without changing the result.
The following examples will be flagged:
/* eslint prefer-arrow-callback: "error" */
foo(function(a) { return a; }); // ERROR
// prefer: foo(a => a)
foo(function() { return this.a; }.bind(this)); // ERROR
// prefer: foo(() => this.a)
Instances where an arrow function would not produce identical results will be ignored.
The following examples will not be flagged:
/* eslint prefer-arrow-callback: "error" */
/* eslint-env es6 */
// arrow function callback
foo(a => a); // OK
// generator as callback
foo(function*() { yield; }); // OK
// function expression not used as callback or function argument
var foo = function foo(a) { return a; }; // OK
// unbound function expression callback
foo(function() { return this.a; }); // OK
// recursive named function callback
foo(function bar(n) { return n && n + bar(n - 1); }); // OK
Options
Access further control over this rule's behavior via an options object.
Default: { allowNamedFunctions: false, allowUnboundThis: true }
allowNamedFunctions
By default { "allowNamedFunctions": false }
, this boolean
option prohibits using named functions as callbacks or function arguments.
Changing this value to true
will reverse this option's behavior by allowing use of named functions without restriction.
{ "allowNamedFunctions": true }
will not flag the following example:
/* eslint prefer-arrow-callback: [ "error", { "allowNamedFunctions": true } ] */
foo(function bar() {});
allowUnboundThis
By default { "allowUnboundThis": true }
, this boolean
option allows function expressions containing this
to be used as callbacks, as long as the function in question has not been explicitly bound.
When set to false
this option prohibits the use of function expressions as callbacks or function arguments entirely, without exception.
{ "allowUnboundThis": false }
will flag the following examples:
/* 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
In environments that have not yet adopted ES6 language features (ES3/5).
In ES6+ environments that allow the use of function expressions when describing callbacks or function arguments.
Further Reading
Unexpected var, use let or const instead. Open
for (var k in serializedObj) {
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
require let
or const
instead of var
(no-var)
ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let
and const
keywords. Block scope is common in many other programming languages and helps programmers avoid mistakes
such as:
var count = people.length;
var enoughFood = count > sandwiches.length;
if (enoughFood) {
var count = sandwiches.length; // accidentally overriding the count variable
console.log("We have " + count + " sandwiches for everyone. Plenty for all!");
}
// our count variable is no longer accurate
console.log("We have " + count + " people and " + sandwiches.length + " sandwiches!");
Rule Details
This rule is aimed at discouraging the use of var
and encouraging the use of const
or let
instead.
Examples
Examples of incorrect code for this rule:
/*eslint no-var: "error"*/
var x = "y";
var CONFIG = {};
Examples of correct code for this rule:
/*eslint no-var: "error"*/
/*eslint-env es6*/
let x = "y";
const CONFIG = {};
When Not To Use It
In addition to non-ES6 environments, existing JavaScript projects that are beginning to introduce ES6 into their
codebase may not want to apply this rule if the cost of migrating from var
to let
is too costly.
Source: http://eslint.org/docs/rules/
A space is required before '}'. Open
miqJqueryRequest(url, {beforeSend: true, data: serializeFields});
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
enforce consistent spacing inside braces (object-curly-spacing)
While formatting preferences are very personal, a number of style guides require or disallow spaces between curly braces in the following situations:
// simple object literals
var obj = { foo: "bar" };
// nested object literals
var obj = { foo: { zoo: "bar" } };
// destructuring assignment (EcmaScript 6)
var { x, y } = y;
// import/export declarations (EcmaScript 6)
import { foo } from "bar";
export { foo };
Rule Details
This rule enforces consistent spacing inside braces of object literals, destructuring assignments, and import/export specifiers.
Options
This rule has two options, a string option and an object option.
String option:
-
"never"
(default) disallows spacing inside of braces -
"always"
requires spacing inside of braces (except{}
)
Object option:
-
"arraysInObjects": true
requires spacing inside of braces of objects beginning and/or ending with an array element (applies when the first option is set tonever
) -
"arraysInObjects": false
disallows spacing inside of braces of objects beginning and/or ending with an array element (applies when the first option is set toalways
) -
"objectsInObjects": true
requires spacing inside of braces of objects beginning and/or ending with an object element (applies when the first option is set tonever
) -
"objectsInObjects": false
disallows spacing inside of braces of objects beginning and/or ending with an object element (applies when the first option is set toalways
)
never
Examples of incorrect code for this rule with the default "never"
option:
/*eslint object-curly-spacing: ["error", "never"]*/
var obj = { 'foo': 'bar' };
var obj = {'foo': 'bar' };
var obj = { baz: {'foo': 'qux'}, bar};
var obj = {baz: { 'foo': 'qux'}, bar};
var {x } = y;
import { foo } from 'bar';
Examples of correct code for this rule with the default "never"
option:
/*eslint object-curly-spacing: ["error", "never"]*/
var obj = {'foo': 'bar'};
var obj = {'foo': {'bar': 'baz'}, 'qux': 'quxx'};
var obj = {
'foo': 'bar'
};
var obj = {'foo': 'bar'
};
var obj = {
'foo':'bar'};
var obj = {};
var {x} = y;
import {foo} from 'bar';
always
Examples of incorrect code for this rule with the "always"
option:
/*eslint object-curly-spacing: ["error", "always"]*/
var obj = {'foo': 'bar'};
var obj = {'foo': 'bar' };
var obj = { baz: {'foo': 'qux'}, bar};
var obj = {baz: { 'foo': 'qux' }, bar};
var obj = {'foo': 'bar'
};
var obj = {
'foo':'bar'};
var {x} = y;
import {foo } from 'bar';
Examples of correct code for this rule with the "always"
option:
/*eslint object-curly-spacing: ["error", "always"]*/
var obj = {};
var obj = { 'foo': 'bar' };
var obj = { 'foo': { 'bar': 'baz' }, 'qux': 'quxx' };
var obj = {
'foo': 'bar'
};
var { x } = y;
import { foo } from 'bar';
arraysInObjects
Examples of additional correct code for this rule with the "never", { "arraysInObjects": true }
options:
/*eslint object-curly-spacing: ["error", "never", { "arraysInObjects": true }]*/
var obj = {"foo": [ 1, 2 ] };
var obj = {"foo": [ "baz", "bar" ] };
Examples of additional correct code for this rule with the "always", { "arraysInObjects": false }
options:
/*eslint object-curly-spacing: ["error", "always", { "arraysInObjects": false }]*/
var obj = { "foo": [ 1, 2 ]};
var obj = { "foo": [ "baz", "bar" ]};
objectsInObjects
Examples of additional correct code for this rule with the "never", { "objectsInObjects": true }
options:
/*eslint object-curly-spacing: ["error", "never", { "objectsInObjects": true }]*/
var obj = {"foo": {"baz": 1, "bar": 2} };
Examples of additional correct code for this rule with the "always", { "objectsInObjects": false }
options:
/*eslint object-curly-spacing: ["error", "always", { "objectsInObjects": false }]*/
var obj = { "foo": { "baz": 1, "bar": 2 }};
When Not To Use It
You can turn this rule off if you are not concerned with the consistency of spacing between curly braces.
Related Rules
- [array-bracket-spacing](array-bracket-spacing.md)
- [comma-spacing](comma-spacing.md)
- [computed-property-spacing](computed-property-spacing.md)
- [space-in-parens](space-in-parens.md) Source: http://eslint.org/docs/rules/
All 'var' declarations must be at the top of the function scope. Open
for (var k in serializedObj) {
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Require Variable Declarations to be at the top of their scope (vars-on-top)
The vars-on-top
rule generates warnings when variable declarations are not used serially at the top of a function scope or the top of a program.
By default variable declarations are always moved (“hoisted”) invisibly to the top of their containing scope by the JavaScript interpreter.
This rule forces the programmer to represent that behavior by manually moving the variable declaration to the top of its containing scope.
Rule Details
This rule aims to keep all variable declarations in the leading series of statements. Allowing multiple declarations helps promote maintainability and is thus allowed.
Examples of incorrect code for this rule:
/*eslint vars-on-top: "error"*/
// Variable declarations in a block:
function doSomething() {
var first;
if (true) {
first = true;
}
var second;
}
// Variable declaration in for initializer:
function doSomething() {
for (var i=0; i<10; i++) {}
}
/*eslint vars-on-top: "error"*/
// Variables after other statements:
f();
var a;
Examples of correct code for this rule:
/*eslint vars-on-top: "error"*/
function doSomething() {
var first;
var second; //multiple declarations are allowed at the top
if (true) {
first = true;
}
}
function doSomething() {
var i;
for (i=0; i<10; i++) {}
}
/*eslint vars-on-top: "error"*/
var a;
f();
/*eslint vars-on-top: "error"*/
// Directives may precede variable declarations.
"use strict";
var a;
f();
// Comments can describe variables.
function doSomething() {
// this is the first var.
var first;
// this is the second var.
var second
}
Further Reading
A space is required before '}'. Open
miqFlashLater({message: message, level: flashType});
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
enforce consistent spacing inside braces (object-curly-spacing)
While formatting preferences are very personal, a number of style guides require or disallow spaces between curly braces in the following situations:
// simple object literals
var obj = { foo: "bar" };
// nested object literals
var obj = { foo: { zoo: "bar" } };
// destructuring assignment (EcmaScript 6)
var { x, y } = y;
// import/export declarations (EcmaScript 6)
import { foo } from "bar";
export { foo };
Rule Details
This rule enforces consistent spacing inside braces of object literals, destructuring assignments, and import/export specifiers.
Options
This rule has two options, a string option and an object option.
String option:
-
"never"
(default) disallows spacing inside of braces -
"always"
requires spacing inside of braces (except{}
)
Object option:
-
"arraysInObjects": true
requires spacing inside of braces of objects beginning and/or ending with an array element (applies when the first option is set tonever
) -
"arraysInObjects": false
disallows spacing inside of braces of objects beginning and/or ending with an array element (applies when the first option is set toalways
) -
"objectsInObjects": true
requires spacing inside of braces of objects beginning and/or ending with an object element (applies when the first option is set tonever
) -
"objectsInObjects": false
disallows spacing inside of braces of objects beginning and/or ending with an object element (applies when the first option is set toalways
)
never
Examples of incorrect code for this rule with the default "never"
option:
/*eslint object-curly-spacing: ["error", "never"]*/
var obj = { 'foo': 'bar' };
var obj = {'foo': 'bar' };
var obj = { baz: {'foo': 'qux'}, bar};
var obj = {baz: { 'foo': 'qux'}, bar};
var {x } = y;
import { foo } from 'bar';
Examples of correct code for this rule with the default "never"
option:
/*eslint object-curly-spacing: ["error", "never"]*/
var obj = {'foo': 'bar'};
var obj = {'foo': {'bar': 'baz'}, 'qux': 'quxx'};
var obj = {
'foo': 'bar'
};
var obj = {'foo': 'bar'
};
var obj = {
'foo':'bar'};
var obj = {};
var {x} = y;
import {foo} from 'bar';
always
Examples of incorrect code for this rule with the "always"
option:
/*eslint object-curly-spacing: ["error", "always"]*/
var obj = {'foo': 'bar'};
var obj = {'foo': 'bar' };
var obj = { baz: {'foo': 'qux'}, bar};
var obj = {baz: { 'foo': 'qux' }, bar};
var obj = {'foo': 'bar'
};
var obj = {
'foo':'bar'};
var {x} = y;
import {foo } from 'bar';
Examples of correct code for this rule with the "always"
option:
/*eslint object-curly-spacing: ["error", "always"]*/
var obj = {};
var obj = { 'foo': 'bar' };
var obj = { 'foo': { 'bar': 'baz' }, 'qux': 'quxx' };
var obj = {
'foo': 'bar'
};
var { x } = y;
import { foo } from 'bar';
arraysInObjects
Examples of additional correct code for this rule with the "never", { "arraysInObjects": true }
options:
/*eslint object-curly-spacing: ["error", "never", { "arraysInObjects": true }]*/
var obj = {"foo": [ 1, 2 ] };
var obj = {"foo": [ "baz", "bar" ] };
Examples of additional correct code for this rule with the "always", { "arraysInObjects": false }
options:
/*eslint object-curly-spacing: ["error", "always", { "arraysInObjects": false }]*/
var obj = { "foo": [ 1, 2 ]};
var obj = { "foo": [ "baz", "bar" ]};
objectsInObjects
Examples of additional correct code for this rule with the "never", { "objectsInObjects": true }
options:
/*eslint object-curly-spacing: ["error", "never", { "objectsInObjects": true }]*/
var obj = {"foo": {"baz": 1, "bar": 2} };
Examples of additional correct code for this rule with the "always", { "objectsInObjects": false }
options:
/*eslint object-curly-spacing: ["error", "always", { "objectsInObjects": false }]*/
var obj = { "foo": { "baz": 1, "bar": 2 }};
When Not To Use It
You can turn this rule off if you are not concerned with the consistency of spacing between curly braces.
Related Rules
- [array-bracket-spacing](array-bracket-spacing.md)
- [comma-spacing](comma-spacing.md)
- [computed-property-spacing](computed-property-spacing.md)
- [space-in-parens](space-in-parens.md) Source: http://eslint.org/docs/rules/
A space is required after '{'. Open
miqJqueryRequest(url, {beforeSend: true, data: serializeFields});
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
enforce consistent spacing inside braces (object-curly-spacing)
While formatting preferences are very personal, a number of style guides require or disallow spaces between curly braces in the following situations:
// simple object literals
var obj = { foo: "bar" };
// nested object literals
var obj = { foo: { zoo: "bar" } };
// destructuring assignment (EcmaScript 6)
var { x, y } = y;
// import/export declarations (EcmaScript 6)
import { foo } from "bar";
export { foo };
Rule Details
This rule enforces consistent spacing inside braces of object literals, destructuring assignments, and import/export specifiers.
Options
This rule has two options, a string option and an object option.
String option:
-
"never"
(default) disallows spacing inside of braces -
"always"
requires spacing inside of braces (except{}
)
Object option:
-
"arraysInObjects": true
requires spacing inside of braces of objects beginning and/or ending with an array element (applies when the first option is set tonever
) -
"arraysInObjects": false
disallows spacing inside of braces of objects beginning and/or ending with an array element (applies when the first option is set toalways
) -
"objectsInObjects": true
requires spacing inside of braces of objects beginning and/or ending with an object element (applies when the first option is set tonever
) -
"objectsInObjects": false
disallows spacing inside of braces of objects beginning and/or ending with an object element (applies when the first option is set toalways
)
never
Examples of incorrect code for this rule with the default "never"
option:
/*eslint object-curly-spacing: ["error", "never"]*/
var obj = { 'foo': 'bar' };
var obj = {'foo': 'bar' };
var obj = { baz: {'foo': 'qux'}, bar};
var obj = {baz: { 'foo': 'qux'}, bar};
var {x } = y;
import { foo } from 'bar';
Examples of correct code for this rule with the default "never"
option:
/*eslint object-curly-spacing: ["error", "never"]*/
var obj = {'foo': 'bar'};
var obj = {'foo': {'bar': 'baz'}, 'qux': 'quxx'};
var obj = {
'foo': 'bar'
};
var obj = {'foo': 'bar'
};
var obj = {
'foo':'bar'};
var obj = {};
var {x} = y;
import {foo} from 'bar';
always
Examples of incorrect code for this rule with the "always"
option:
/*eslint object-curly-spacing: ["error", "always"]*/
var obj = {'foo': 'bar'};
var obj = {'foo': 'bar' };
var obj = { baz: {'foo': 'qux'}, bar};
var obj = {baz: { 'foo': 'qux' }, bar};
var obj = {'foo': 'bar'
};
var obj = {
'foo':'bar'};
var {x} = y;
import {foo } from 'bar';
Examples of correct code for this rule with the "always"
option:
/*eslint object-curly-spacing: ["error", "always"]*/
var obj = {};
var obj = { 'foo': 'bar' };
var obj = { 'foo': { 'bar': 'baz' }, 'qux': 'quxx' };
var obj = {
'foo': 'bar'
};
var { x } = y;
import { foo } from 'bar';
arraysInObjects
Examples of additional correct code for this rule with the "never", { "arraysInObjects": true }
options:
/*eslint object-curly-spacing: ["error", "never", { "arraysInObjects": true }]*/
var obj = {"foo": [ 1, 2 ] };
var obj = {"foo": [ "baz", "bar" ] };
Examples of additional correct code for this rule with the "always", { "arraysInObjects": false }
options:
/*eslint object-curly-spacing: ["error", "always", { "arraysInObjects": false }]*/
var obj = { "foo": [ 1, 2 ]};
var obj = { "foo": [ "baz", "bar" ]};
objectsInObjects
Examples of additional correct code for this rule with the "never", { "objectsInObjects": true }
options:
/*eslint object-curly-spacing: ["error", "never", { "objectsInObjects": true }]*/
var obj = {"foo": {"baz": 1, "bar": 2} };
Examples of additional correct code for this rule with the "always", { "objectsInObjects": false }
options:
/*eslint object-curly-spacing: ["error", "always", { "objectsInObjects": false }]*/
var obj = { "foo": { "baz": 1, "bar": 2 }};
When Not To Use It
You can turn this rule off if you are not concerned with the consistency of spacing between curly braces.
Related Rules
- [array-bracket-spacing](array-bracket-spacing.md)
- [comma-spacing](comma-spacing.md)
- [computed-property-spacing](computed-property-spacing.md)
- [space-in-parens](space-in-parens.md) Source: http://eslint.org/docs/rules/
Use object destructuring. Open
message = e.error.message;
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Prefer destructuring from arrays and objects (prefer-destructuring)
With JavaScript ES6, a new syntax was added for creating variables from an array index or object property, called destructuring. This rule enforces usage of destructuring instead of accessing a property through a member expression.
Rule Details
Options
This rule takes two sets of configuration objects. The first object parameter determines what types of destructuring the rule applies to.
The two properties, array
and object
, can be used to turn on or off the destructuring requirement for each of those types independently. By default, both are true.
Alternatively, you can use separate configurations for different assignment types. It accepts 2 other keys instead of array
and object
.
One key is VariableDeclarator
and the other is AssignmentExpression
, which can be used to control the destructuring requirement for each of those types independently. Each property accepts an object that accepts two properties, array
and object
, which can be used to control the destructuring requirement for each of array
and object
independently for variable declarations and assignment expressions. By default, array
and object
are set to true for both VariableDeclarator
and AssignmentExpression
.
The rule has a second object with a single key, enforceForRenamedProperties
, which determines whether the object
destructuring applies to renamed variables.
Examples of incorrect code for this rule:
// With `array` enabled
var foo = array[0];
// With `object` enabled
var foo = object.foo;
var foo = object['foo'];
Examples of correct code for this rule:
// With `array` enabled
var [ foo ] = array;
var foo = array[someIndex];
// With `object` enabled
var { foo } = object;
var foo = object.bar;
let foo;
({ foo } = object);
Examples of incorrect code when enforceForRenamedProperties
is enabled:
var foo = object.bar;
Examples of correct code when enforceForRenamedProperties
is enabled:
var { bar: foo } = object;
An example configuration, with the defaults array
and object
filled in, looks like this:
{
"rules": {
"prefer-destructuring": ["error", {
"array": true,
"object": true
}, {
"enforceForRenamedProperties": false
}]
}
}
The two properties, array
and object
, which can be used to turn on or off the destructuring requirement for each of those types independently. By default, both are true.
For example, the following configuration enforces only object destructuring, but not array destructuring:
{
"rules": {
"prefer-destructuring": ["error", {"object": true, "array": false}]
}
}
An example configuration, with the defaults VariableDeclarator
and AssignmentExpression
filled in, looks like this:
{
"rules": {
"prefer-destructuring": ["error", {
"VariableDeclarator": {
"array": false,
"object": true
},
"AssignmentExpression": {
"array": true,
"object": true
}
}, {
"enforceForRenamedProperties": false
}]
}
}
The two properties, VariableDeclarator
and AssignmentExpression
, which can be used to turn on or off the destructuring requirement for array
and object
. By default, all values are true.
For example, the following configuration enforces object destructuring in variable declarations and enforces array destructuring in assignment expressions.
{
"rules": {
"prefer-destructuring": ["error", {
"VariableDeclarator": {
"array": false,
"object": true
},
"AssignmentExpression": {
"array": true,
"object": false
}
}, {
"enforceForRenamedProperties": false
}]
}
}
Examples of correct code when object destructuring in VariableDeclarator
is enforced:
/* eslint prefer-destructuring: ["error", {VariableDeclarator: {object: true}}] */
var {bar: foo} = object;
Examples of correct code when array destructuring in AssignmentExpression
is enforced:
/* eslint prefer-destructuring: ["error", {AssignmentExpression: {array: true}}] */
[bar] = array;
When Not To Use It
If you want to be able to access array indices or object properties directly, you can either configure the rule to your tastes or disable the rule entirely.
Additionally, if you intend to access large array indices directly, like:
var foo = array[100];
Then the array
part of this rule is not recommended, as destructuring does not match this use case very well.
Or for non-iterable 'array-like' objects:
var $ = require('jquery');
var foo = $('body')[0];
var [bar] = $('body'); // fails with a TypeError
Further Reading
If you want to learn more about destructuring, check out the links below:
Unexpected string concatenation. Open
API.get('/api/cloud_networks?expand=resources&attributes=name,ems_ref&filter[]=external_facing=true&filter[]=ems_id=' + id)
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
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.
Related Rules
- [no-useless-concat](no-useless-concat.md)
- [quotes](quotes.md) Source: http://eslint.org/docs/rules/
A space is required after '{'. Open
miqFlashLater({message: message, level: flashType});
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
enforce consistent spacing inside braces (object-curly-spacing)
While formatting preferences are very personal, a number of style guides require or disallow spaces between curly braces in the following situations:
// simple object literals
var obj = { foo: "bar" };
// nested object literals
var obj = { foo: { zoo: "bar" } };
// destructuring assignment (EcmaScript 6)
var { x, y } = y;
// import/export declarations (EcmaScript 6)
import { foo } from "bar";
export { foo };
Rule Details
This rule enforces consistent spacing inside braces of object literals, destructuring assignments, and import/export specifiers.
Options
This rule has two options, a string option and an object option.
String option:
-
"never"
(default) disallows spacing inside of braces -
"always"
requires spacing inside of braces (except{}
)
Object option:
-
"arraysInObjects": true
requires spacing inside of braces of objects beginning and/or ending with an array element (applies when the first option is set tonever
) -
"arraysInObjects": false
disallows spacing inside of braces of objects beginning and/or ending with an array element (applies when the first option is set toalways
) -
"objectsInObjects": true
requires spacing inside of braces of objects beginning and/or ending with an object element (applies when the first option is set tonever
) -
"objectsInObjects": false
disallows spacing inside of braces of objects beginning and/or ending with an object element (applies when the first option is set toalways
)
never
Examples of incorrect code for this rule with the default "never"
option:
/*eslint object-curly-spacing: ["error", "never"]*/
var obj = { 'foo': 'bar' };
var obj = {'foo': 'bar' };
var obj = { baz: {'foo': 'qux'}, bar};
var obj = {baz: { 'foo': 'qux'}, bar};
var {x } = y;
import { foo } from 'bar';
Examples of correct code for this rule with the default "never"
option:
/*eslint object-curly-spacing: ["error", "never"]*/
var obj = {'foo': 'bar'};
var obj = {'foo': {'bar': 'baz'}, 'qux': 'quxx'};
var obj = {
'foo': 'bar'
};
var obj = {'foo': 'bar'
};
var obj = {
'foo':'bar'};
var obj = {};
var {x} = y;
import {foo} from 'bar';
always
Examples of incorrect code for this rule with the "always"
option:
/*eslint object-curly-spacing: ["error", "always"]*/
var obj = {'foo': 'bar'};
var obj = {'foo': 'bar' };
var obj = { baz: {'foo': 'qux'}, bar};
var obj = {baz: { 'foo': 'qux' }, bar};
var obj = {'foo': 'bar'
};
var obj = {
'foo':'bar'};
var {x} = y;
import {foo } from 'bar';
Examples of correct code for this rule with the "always"
option:
/*eslint object-curly-spacing: ["error", "always"]*/
var obj = {};
var obj = { 'foo': 'bar' };
var obj = { 'foo': { 'bar': 'baz' }, 'qux': 'quxx' };
var obj = {
'foo': 'bar'
};
var { x } = y;
import { foo } from 'bar';
arraysInObjects
Examples of additional correct code for this rule with the "never", { "arraysInObjects": true }
options:
/*eslint object-curly-spacing: ["error", "never", { "arraysInObjects": true }]*/
var obj = {"foo": [ 1, 2 ] };
var obj = {"foo": [ "baz", "bar" ] };
Examples of additional correct code for this rule with the "always", { "arraysInObjects": false }
options:
/*eslint object-curly-spacing: ["error", "always", { "arraysInObjects": false }]*/
var obj = { "foo": [ 1, 2 ]};
var obj = { "foo": [ "baz", "bar" ]};
objectsInObjects
Examples of additional correct code for this rule with the "never", { "objectsInObjects": true }
options:
/*eslint object-curly-spacing: ["error", "never", { "objectsInObjects": true }]*/
var obj = {"foo": {"baz": 1, "bar": 2} };
Examples of additional correct code for this rule with the "always", { "objectsInObjects": false }
options:
/*eslint object-curly-spacing: ["error", "always", { "objectsInObjects": false }]*/
var obj = { "foo": { "baz": 1, "bar": 2 }};
When Not To Use It
You can turn this rule off if you are not concerned with the consistency of spacing between curly braces.
Related Rules
- [array-bracket-spacing](array-bracket-spacing.md)
- [comma-spacing](comma-spacing.md)
- [computed-property-spacing](computed-property-spacing.md)
- [space-in-parens](space-in-parens.md) Source: http://eslint.org/docs/rules/
Use object destructuring. Open
message = e.message;
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Prefer destructuring from arrays and objects (prefer-destructuring)
With JavaScript ES6, a new syntax was added for creating variables from an array index or object property, called destructuring. This rule enforces usage of destructuring instead of accessing a property through a member expression.
Rule Details
Options
This rule takes two sets of configuration objects. The first object parameter determines what types of destructuring the rule applies to.
The two properties, array
and object
, can be used to turn on or off the destructuring requirement for each of those types independently. By default, both are true.
Alternatively, you can use separate configurations for different assignment types. It accepts 2 other keys instead of array
and object
.
One key is VariableDeclarator
and the other is AssignmentExpression
, which can be used to control the destructuring requirement for each of those types independently. Each property accepts an object that accepts two properties, array
and object
, which can be used to control the destructuring requirement for each of array
and object
independently for variable declarations and assignment expressions. By default, array
and object
are set to true for both VariableDeclarator
and AssignmentExpression
.
The rule has a second object with a single key, enforceForRenamedProperties
, which determines whether the object
destructuring applies to renamed variables.
Examples of incorrect code for this rule:
// With `array` enabled
var foo = array[0];
// With `object` enabled
var foo = object.foo;
var foo = object['foo'];
Examples of correct code for this rule:
// With `array` enabled
var [ foo ] = array;
var foo = array[someIndex];
// With `object` enabled
var { foo } = object;
var foo = object.bar;
let foo;
({ foo } = object);
Examples of incorrect code when enforceForRenamedProperties
is enabled:
var foo = object.bar;
Examples of correct code when enforceForRenamedProperties
is enabled:
var { bar: foo } = object;
An example configuration, with the defaults array
and object
filled in, looks like this:
{
"rules": {
"prefer-destructuring": ["error", {
"array": true,
"object": true
}, {
"enforceForRenamedProperties": false
}]
}
}
The two properties, array
and object
, which can be used to turn on or off the destructuring requirement for each of those types independently. By default, both are true.
For example, the following configuration enforces only object destructuring, but not array destructuring:
{
"rules": {
"prefer-destructuring": ["error", {"object": true, "array": false}]
}
}
An example configuration, with the defaults VariableDeclarator
and AssignmentExpression
filled in, looks like this:
{
"rules": {
"prefer-destructuring": ["error", {
"VariableDeclarator": {
"array": false,
"object": true
},
"AssignmentExpression": {
"array": true,
"object": true
}
}, {
"enforceForRenamedProperties": false
}]
}
}
The two properties, VariableDeclarator
and AssignmentExpression
, which can be used to turn on or off the destructuring requirement for array
and object
. By default, all values are true.
For example, the following configuration enforces object destructuring in variable declarations and enforces array destructuring in assignment expressions.
{
"rules": {
"prefer-destructuring": ["error", {
"VariableDeclarator": {
"array": false,
"object": true
},
"AssignmentExpression": {
"array": true,
"object": false
}
}, {
"enforceForRenamedProperties": false
}]
}
}
Examples of correct code when object destructuring in VariableDeclarator
is enforced:
/* eslint prefer-destructuring: ["error", {VariableDeclarator: {object: true}}] */
var {bar: foo} = object;
Examples of correct code when array destructuring in AssignmentExpression
is enforced:
/* eslint prefer-destructuring: ["error", {AssignmentExpression: {array: true}}] */
[bar] = array;
When Not To Use It
If you want to be able to access array indices or object properties directly, you can either configure the rule to your tastes or disable the rule entirely.
Additionally, if you intend to access large array indices directly, like:
var foo = array[100];
Then the array
part of this rule is not recommended, as destructuring does not match this use case very well.
Or for non-iterable 'array-like' objects:
var $ = require('jquery');
var foo = $('body')[0];
var [bar] = $('body'); // fails with a TypeError
Further Reading
If you want to learn more about destructuring, check out the links below:
Unexpected string concatenation. Open
API.get('/api/providers/' + id + '/cloud_tenants?expand=resources&attributes=id,name')
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
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.
Related Rules
- [no-useless-concat](no-useless-concat.md)
- [quotes](quotes.md) Source: http://eslint.org/docs/rules/
Use object destructuring. Open
message = e.data.error.message;
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Prefer destructuring from arrays and objects (prefer-destructuring)
With JavaScript ES6, a new syntax was added for creating variables from an array index or object property, called destructuring. This rule enforces usage of destructuring instead of accessing a property through a member expression.
Rule Details
Options
This rule takes two sets of configuration objects. The first object parameter determines what types of destructuring the rule applies to.
The two properties, array
and object
, can be used to turn on or off the destructuring requirement for each of those types independently. By default, both are true.
Alternatively, you can use separate configurations for different assignment types. It accepts 2 other keys instead of array
and object
.
One key is VariableDeclarator
and the other is AssignmentExpression
, which can be used to control the destructuring requirement for each of those types independently. Each property accepts an object that accepts two properties, array
and object
, which can be used to control the destructuring requirement for each of array
and object
independently for variable declarations and assignment expressions. By default, array
and object
are set to true for both VariableDeclarator
and AssignmentExpression
.
The rule has a second object with a single key, enforceForRenamedProperties
, which determines whether the object
destructuring applies to renamed variables.
Examples of incorrect code for this rule:
// With `array` enabled
var foo = array[0];
// With `object` enabled
var foo = object.foo;
var foo = object['foo'];
Examples of correct code for this rule:
// With `array` enabled
var [ foo ] = array;
var foo = array[someIndex];
// With `object` enabled
var { foo } = object;
var foo = object.bar;
let foo;
({ foo } = object);
Examples of incorrect code when enforceForRenamedProperties
is enabled:
var foo = object.bar;
Examples of correct code when enforceForRenamedProperties
is enabled:
var { bar: foo } = object;
An example configuration, with the defaults array
and object
filled in, looks like this:
{
"rules": {
"prefer-destructuring": ["error", {
"array": true,
"object": true
}, {
"enforceForRenamedProperties": false
}]
}
}
The two properties, array
and object
, which can be used to turn on or off the destructuring requirement for each of those types independently. By default, both are true.
For example, the following configuration enforces only object destructuring, but not array destructuring:
{
"rules": {
"prefer-destructuring": ["error", {"object": true, "array": false}]
}
}
An example configuration, with the defaults VariableDeclarator
and AssignmentExpression
filled in, looks like this:
{
"rules": {
"prefer-destructuring": ["error", {
"VariableDeclarator": {
"array": false,
"object": true
},
"AssignmentExpression": {
"array": true,
"object": true
}
}, {
"enforceForRenamedProperties": false
}]
}
}
The two properties, VariableDeclarator
and AssignmentExpression
, which can be used to turn on or off the destructuring requirement for array
and object
. By default, all values are true.
For example, the following configuration enforces object destructuring in variable declarations and enforces array destructuring in assignment expressions.
{
"rules": {
"prefer-destructuring": ["error", {
"VariableDeclarator": {
"array": false,
"object": true
},
"AssignmentExpression": {
"array": true,
"object": false
}
}, {
"enforceForRenamedProperties": false
}]
}
}
Examples of correct code when object destructuring in VariableDeclarator
is enforced:
/* eslint prefer-destructuring: ["error", {VariableDeclarator: {object: true}}] */
var {bar: foo} = object;
Examples of correct code when array destructuring in AssignmentExpression
is enforced:
/* eslint prefer-destructuring: ["error", {AssignmentExpression: {array: true}}] */
[bar] = array;
When Not To Use It
If you want to be able to access array indices or object properties directly, you can either configure the rule to your tastes or disable the rule entirely.
Additionally, if you intend to access large array indices directly, like:
var foo = array[100];
Then the array
part of this rule is not recommended, as destructuring does not match this use case very well.
Or for non-iterable 'array-like' objects:
var $ = require('jquery');
var foo = $('body')[0];
var [bar] = $('body'); // fails with a TypeError
Further Reading
If you want to learn more about destructuring, check out the links below:
Expected to return a value at the end of function. Open
this.validateWithREST = function($event, credType, url, formSubmit) {
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
require return
statements to either always or never specify values (consistent-return)
Unlike statically-typed languages which enforce that a function returns a specified type of value, JavaScript allows different code paths in a function to return different types of values.
A confusing aspect of JavaScript is that a function returns undefined
if any of the following are true:
- it does not execute a
return
statement before it exits - it executes
return
which does not specify a value explicitly - it executes
return undefined
- it executes
return void
followed by an expression (for example, a function call) - it executes
return
followed by any other expression which evaluates toundefined
If any code paths in a function return a value explicitly but some code path do not return a value explicitly, it might be a typing mistake, especially in a large function. In the following example:
- a code path through the function returns a Boolean value
true
- another code path does not return a value explicitly, therefore returns
undefined
implicitly
function doSomething(condition) {
if (condition) {
return true;
} else {
return;
}
}
Rule Details
This rule requires return
statements to either always or never specify values. This rule ignores function definitions where the name begins with an uppercase letter, because constructors (when invoked with the new
operator) return the instantiated object implicitly if they do not return another object explicitly.
Examples of incorrect code for this rule:
/*eslint consistent-return: "error"*/
function doSomething(condition) {
if (condition) {
return true;
} else {
return;
}
}
function doSomething(condition) {
if (condition) {
return true;
}
}
Examples of correct code for this rule:
/*eslint consistent-return: "error"*/
function doSomething(condition) {
if (condition) {
return true;
} else {
return false;
}
}
function Foo() {
if (!(this instanceof Foo)) {
return new Foo();
}
this.a = 0;
}
Options
This rule has an object option:
-
"treatUndefinedAsUnspecified": false
(default) always either specify values or returnundefined
implicitly only. -
"treatUndefinedAsUnspecified": true
always either specify values or returnundefined
explicitly or implicitly.
treatUndefinedAsUnspecified
Examples of incorrect code for this rule with the default { "treatUndefinedAsUnspecified": false }
option:
/*eslint consistent-return: ["error", { "treatUndefinedAsUnspecified": false }]*/
function foo(callback) {
if (callback) {
return void callback();
}
// no return statement
}
function bar(condition) {
if (condition) {
return undefined;
}
// no return statement
}
Examples of incorrect code for this rule with the { "treatUndefinedAsUnspecified": true }
option:
/*eslint consistent-return: ["error", { "treatUndefinedAsUnspecified": true }]*/
function foo(callback) {
if (callback) {
return void callback();
}
return true;
}
function bar(condition) {
if (condition) {
return undefined;
}
return true;
}
Examples of correct code for this rule with the { "treatUndefinedAsUnspecified": true }
option:
/*eslint consistent-return: ["error", { "treatUndefinedAsUnspecified": true }]*/
function foo(callback) {
if (callback) {
return void callback();
}
// no return statement
}
function bar(condition) {
if (condition) {
return undefined;
}
// no return statement
}
When Not To Use It
If you want to allow functions to have different return
behavior depending on code branching, then it is safe to disable this rule.
Source: http://eslint.org/docs/rules/
for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array. Open
for (var k in serializedObj) {
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
disallow specified syntax (no-restricted-syntax)
JavaScript has a lot of language features, and not everyone likes all of them. As a result, some projects choose to disallow the use of certain language features altogether. For instance, you might decide to disallow the use of try-catch
or class
, or you might decide to disallow the use of the in
operator.
Rather than creating separate rules for every language feature you want to turn off, this rule allows you to configure the syntax elements you want to restrict use of. These elements are represented by their ESTree node types. For example, a function declaration is represented by FunctionDeclaration
and the with
statement is represented by WithStatement
. You may find the full list of AST node names you can use on GitHub and use the online parser to see what type of nodes your code consists of.
You can also specify [AST selectors](../developer-guide/selectors) to restrict, allowing much more precise control over syntax patterns.
Rule Details
This rule disallows specified (that is, user-defined) syntax.
Options
This rule takes a list of strings, where each string is an AST selector:
{
"rules": {
"no-restricted-syntax": ["error", "FunctionExpression", "WithStatement", "BinaryExpression[operator='in']"]
}
}
Alternatively, the rule also accepts objects, where the selector and an optional custom message are specified:
{
"rules": {
"no-restricted-syntax": [
"error",
{
"selector": "FunctionExpression",
"message": "Function expressions are not allowed."
},
{
"selector": "CallExpression[callee.name='setTimeout'][arguments.length!=2]",
"message": "setTimeout must always be invoked with two arguments."
}
]
}
}
If a custom message is specified with the message
property, ESLint will use that message when reporting occurrences of the syntax specified in the selector
property.
The string and object formats can be freely mixed in the configuration as needed.
Examples of incorrect code for this rule with the "FunctionExpression", "WithStatement", BinaryExpression[operator='in']
options:
/* eslint no-restricted-syntax: ["error", "FunctionExpression", "WithStatement", "BinaryExpression[operator='in']"] */
with (me) {
dontMess();
}
var doSomething = function () {};
foo in bar;
Examples of correct code for this rule with the "FunctionExpression", "WithStatement", BinaryExpression[operator='in']
options:
/* eslint no-restricted-syntax: ["error", "FunctionExpression", "WithStatement", "BinaryExpression[operator='in']"] */
me.dontMess();
function doSomething() {};
foo instanceof bar;
When Not To Use It
If you don't want to restrict your code from using any JavaScript features or syntax, you should not use this rule.
Related Rules
- [no-alert](no-alert.md)
- [no-console](no-console.md)
- [no-debugger](no-debugger.md)
- [no-restricted-properties](no-restricted-properties.md) Source: http://eslint.org/docs/rules/
for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array. Open
for (var k in serializedObj) {
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
disallow specified syntax (no-restricted-syntax)
JavaScript has a lot of language features, and not everyone likes all of them. As a result, some projects choose to disallow the use of certain language features altogether. For instance, you might decide to disallow the use of try-catch
or class
, or you might decide to disallow the use of the in
operator.
Rather than creating separate rules for every language feature you want to turn off, this rule allows you to configure the syntax elements you want to restrict use of. These elements are represented by their ESTree node types. For example, a function declaration is represented by FunctionDeclaration
and the with
statement is represented by WithStatement
. You may find the full list of AST node names you can use on GitHub and use the online parser to see what type of nodes your code consists of.
You can also specify [AST selectors](../developer-guide/selectors) to restrict, allowing much more precise control over syntax patterns.
Rule Details
This rule disallows specified (that is, user-defined) syntax.
Options
This rule takes a list of strings, where each string is an AST selector:
{
"rules": {
"no-restricted-syntax": ["error", "FunctionExpression", "WithStatement", "BinaryExpression[operator='in']"]
}
}
Alternatively, the rule also accepts objects, where the selector and an optional custom message are specified:
{
"rules": {
"no-restricted-syntax": [
"error",
{
"selector": "FunctionExpression",
"message": "Function expressions are not allowed."
},
{
"selector": "CallExpression[callee.name='setTimeout'][arguments.length!=2]",
"message": "setTimeout must always be invoked with two arguments."
}
]
}
}
If a custom message is specified with the message
property, ESLint will use that message when reporting occurrences of the syntax specified in the selector
property.
The string and object formats can be freely mixed in the configuration as needed.
Examples of incorrect code for this rule with the "FunctionExpression", "WithStatement", BinaryExpression[operator='in']
options:
/* eslint no-restricted-syntax: ["error", "FunctionExpression", "WithStatement", "BinaryExpression[operator='in']"] */
with (me) {
dontMess();
}
var doSomething = function () {};
foo in bar;
Examples of correct code for this rule with the "FunctionExpression", "WithStatement", BinaryExpression[operator='in']
options:
/* eslint no-restricted-syntax: ["error", "FunctionExpression", "WithStatement", "BinaryExpression[operator='in']"] */
me.dontMess();
function doSomething() {};
foo instanceof bar;
When Not To Use It
If you don't want to restrict your code from using any JavaScript features or syntax, you should not use this rule.
Related Rules
- [no-alert](no-alert.md)
- [no-console](no-console.md)
- [no-debugger](no-debugger.md)
- [no-restricted-properties](no-restricted-properties.md) Source: http://eslint.org/docs/rules/
Do not access Object.prototype method 'hasOwnProperty' from target object. Open
if (serializedObj.hasOwnProperty(k) && !serializedObj[k]) {
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Disallow use of Object.prototypes builtins directly (no-prototype-builtins)
In ECMAScript 5.1, Object.create
was added, which enables the creation of objects with a specified [[Prototype]]
. Object.create(null)
is a common pattern used to create objects that will be used as a Map. This can lead to errors when it is assumed that objects will have properties from Object.prototype
. This rule prevents calling some Object.prototype
methods directly from an object.
Additionally, objects can have properties that shadow the builtins on Object.prototype
, potentially causing unintended behavior or denial-of-service security vulnerabilities. For example, it would be unsafe for a webserver to parse JSON input from a client and call hasOwnProperty
directly on the resulting object, because a malicious client could send a JSON value like {"hasOwnProperty": 1}
and cause the server to crash.
To avoid subtle bugs like this, it's better to always call these methods from Object.prototype
. For example, foo.hasOwnProperty("bar")
should be replaced with Object.prototype.hasOwnProperty.call(foo, "bar")
.
Rule Details
This rule disallows calling some Object.prototype
methods directly on object instances.
Examples of incorrect code for this rule:
/*eslint no-prototype-builtins: "error"*/
var hasBarProperty = foo.hasOwnProperty("bar");
var isPrototypeOfBar = foo.isPrototypeOf(bar);
var barIsEnumerable = foo.propertyIsEnumerable("bar");
Examples of correct code for this rule:
/*eslint no-prototype-builtins: "error"*/
var hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar");
var isPrototypeOfBar = Object.prototype.isPrototypeOf.call(foo, bar);
var barIsEnumerable = {}.propertyIsEnumerable.call(foo, "bar");
When Not To Use It
You may want to turn this rule off if your code only touches objects with hardcoded keys, and you will never use an object that shadows an Object.prototype
method or which does not inherit from Object.prototype
.
Source: http://eslint.org/docs/rules/
Do not access Object.prototype method 'hasOwnProperty' from target object. Open
if ((ignoredFields.indexOf(k) >= 0) || (serializedObj.hasOwnProperty(k) && !serializedObj[k])) {
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Disallow use of Object.prototypes builtins directly (no-prototype-builtins)
In ECMAScript 5.1, Object.create
was added, which enables the creation of objects with a specified [[Prototype]]
. Object.create(null)
is a common pattern used to create objects that will be used as a Map. This can lead to errors when it is assumed that objects will have properties from Object.prototype
. This rule prevents calling some Object.prototype
methods directly from an object.
Additionally, objects can have properties that shadow the builtins on Object.prototype
, potentially causing unintended behavior or denial-of-service security vulnerabilities. For example, it would be unsafe for a webserver to parse JSON input from a client and call hasOwnProperty
directly on the resulting object, because a malicious client could send a JSON value like {"hasOwnProperty": 1}
and cause the server to crash.
To avoid subtle bugs like this, it's better to always call these methods from Object.prototype
. For example, foo.hasOwnProperty("bar")
should be replaced with Object.prototype.hasOwnProperty.call(foo, "bar")
.
Rule Details
This rule disallows calling some Object.prototype
methods directly on object instances.
Examples of incorrect code for this rule:
/*eslint no-prototype-builtins: "error"*/
var hasBarProperty = foo.hasOwnProperty("bar");
var isPrototypeOfBar = foo.isPrototypeOf(bar);
var barIsEnumerable = foo.propertyIsEnumerable("bar");
Examples of correct code for this rule:
/*eslint no-prototype-builtins: "error"*/
var hasBarProperty = Object.prototype.hasOwnProperty.call(foo, "bar");
var isPrototypeOfBar = Object.prototype.isPrototypeOf.call(foo, bar);
var barIsEnumerable = {}.propertyIsEnumerable.call(foo, "bar");
When Not To Use It
You may want to turn this rule off if your code only touches objects with hardcoded keys, and you will never use an object that shadows an Object.prototype
method or which does not inherit from Object.prototype
.
Source: http://eslint.org/docs/rules/
Identical blocks of code found in 2 locations. Consider refactoring. Open
if (e.data && e.data.error && e.data.error.message) {
message = e.data.error.message;
} else if (e.error && e.error.message) {
message = e.error.message;
} else if (e.message) {
- Read upRead up
- Create a ticketCreate a ticket
Duplicated Code
Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).
Tuning
This issue has a mass of 120.
We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.
The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.
If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.
See codeclimate-duplication
's documentation for more information about tuning the mass threshold in your .codeclimate.yml
.
Refactorings
- Extract Method
- Extract Class
- Form Template Method
- Introduce Null Object
- Pull Up Method
- Pull Up Field
- Substitute Algorithm
Further Reading
- Don't Repeat Yourself on the C2 Wiki
- Duplicated Code on SourceMaking
- Refactoring: Improving the Design of Existing Code by Martin Fowler. Duplicated Code, p76