diff --git a/rules/no-for-loop.js b/rules/no-for-loop.js index 283ace5367..623f260907 100644 --- a/rules/no-for-loop.js +++ b/rules/no-for-loop.js @@ -2,6 +2,7 @@ const getDocumentationUrl = require('./utils/get-documentation-url'); const isLiteralValue = require('./utils/is-literal-value'); const {flatten} = require('lodash'); +const avoidCapture = require('./utils/avoid-capture'); const defaultElementName = 'element'; const isLiteralZero = node => isLiteralValue(node, 0); @@ -335,7 +336,7 @@ const create = context => { const shouldGenerateIndex = isIndexVariableUsedElsewhereInTheLoopBody(indexVariable, bodyScope, arrayIdentifierName); const index = indexIdentifierName; - const element = elementIdentifierName || defaultElementName; + const element = elementIdentifierName || avoidCapture(defaultElementName, [bodyScope], context.parserOptions.ecmaVersion); const array = arrayIdentifierName; let declarationElement = element; diff --git a/test/no-for-loop.js b/test/no-for-loop.js index 24dfcdbfd3..a7467708ed 100644 --- a/test/no-for-loop.js +++ b/test/no-for-loop.js @@ -482,7 +482,42 @@ ruleTester.run('no-for-loop', rule, { const [ a, b ] = element; console.log(a, b, element); } - `) + `), + + // Avoid naming collision when using default element name. + testCase(outdent` + for (let i = 0; i < arr.length; i += 1) { + console.log(arr[i]); + const element = foo(); + console.log(element); + } + `, outdent` + for (const element_ of arr) { + console.log(element_); + const element = foo(); + console.log(element); + } + `), + + // Avoid naming collision when using default element name (multiple collisions). + testCase(outdent` + for (let i = 0; i < arr.length; i += 1) { + console.log(arr[i]); + const element = foo(); + const element_ = foo(); + console.log(element); + console.log(element_); + } + `, outdent` + for (const element__ of arr) { + console.log(element__); + const element = foo(); + const element_ = foo(); + console.log(element); + console.log(element_); + } + `), + ] });