diff --git a/lib/rules/no-unused-vars.js b/lib/rules/no-unused-vars.js index 6f36813aca5..0c54b26fc29 100644 --- a/lib/rules/no-unused-vars.js +++ b/lib/rules/no-unused-vars.js @@ -223,6 +223,32 @@ module.exports = { return false; } + /** + * Gets a list of function definitions for a specified variable. + * @param {Variable} variable - eslint-scope variable object. + * @returns {ASTNode[]} Function nodes. + * @private + */ + function getFunctionDefinitions(variable) { + const functionDefinitions = []; + + variable.defs.forEach(def => { + const { type, node } = def; + + // FunctionDeclarations + if (type === "FunctionName") { + functionDefinitions.push(node); + } + + // FunctionExpressions + if (type === "Variable" && node.init && + (node.init.type === "FunctionExpression" || node.init.type === "ArrowFunctionExpression")) { + functionDefinitions.push(node.init); + } + }); + return functionDefinitions; + } + /** * Checks the position of given nodes. * @@ -435,7 +461,7 @@ module.exports = { * @private */ function isUsedVariable(variable) { - const functionNodes = variable.defs.filter(def => def.type === "FunctionName").map(def => def.node), + const functionNodes = getFunctionDefinitions(variable), isFunctionDefinition = functionNodes.length > 0; let rhsNode = null; diff --git a/tests/lib/rules/no-unused-vars.js b/tests/lib/rules/no-unused-vars.js index 316df18e09a..9b6733cacc3 100644 --- a/tests/lib/rules/no-unused-vars.js +++ b/tests/lib/rules/no-unused-vars.js @@ -274,8 +274,19 @@ ruleTester.run("no-unused-vars", rule, { }, // https://github.com/eslint/eslint/issues/10952 - "/*eslint use-every-a:1*/ !function(b, a) { return 1 }" + "/*eslint use-every-a:1*/ !function(b, a) { return 1 }", + // https://github.com/eslint/eslint/issues/10982 + "var a = function () { a(); }; a();", + "var a = function(){ return function () { a(); } }; a();", + { + code: "const a = () => { a(); }; a();", + parserOptions: { ecmaVersion: 2015 } + }, + { + code: "const a = () => () => { a(); }; a();", + parserOptions: { ecmaVersion: 2015 } + } ], invalid: [ { code: "function foox() { return foox(); }", errors: [definedError("foox")] }, @@ -717,6 +728,28 @@ ruleTester.run("no-unused-vars", rule, { code: "(function(_a) {})();", options: [{ args: "all", caughtErrorsIgnorePattern: "^_" }], errors: [{ message: "'_a' is defined but never used." }] + }, + + // https://github.com/eslint/eslint/issues/10982 + { + code: "var a = function() { a(); };", + errors: [{ message: "'a' is assigned a value but never used." }] + }, + { + code: "var a = function(){ return function() { a(); } };", + errors: [ + { message: "'a' is assigned a value but never used." } + ] + }, + { + code: "const a = () => { a(); };", + parserOptions: { ecmaVersion: 2015 }, + errors: [{ message: "'a' is assigned a value but never used." }] + }, + { + code: "const a = () => () => { a(); };", + parserOptions: { ecmaVersion: 2015 }, + errors: [{ message: "'a' is assigned a value but never used." }] } ] });