diff --git a/lib/.eslintrc b/lib/.eslintrc index 341e9327c7cf3a..e8336884566ccd 100644 --- a/lib/.eslintrc +++ b/lib/.eslintrc @@ -1,3 +1,4 @@ rules: # Custom rules in tools/eslint-rules require-buffer: 2 + no-let-in-for-declaration: 2 diff --git a/tools/eslint-rules/no-let-in-for-declaration.js b/tools/eslint-rules/no-let-in-for-declaration.js new file mode 100644 index 00000000000000..8b1a6783e0773d --- /dev/null +++ b/tools/eslint-rules/no-let-in-for-declaration.js @@ -0,0 +1,46 @@ +/** + * @fileoverview Prohibit the use of `let` as the loop variable + * in the initialization of for, and the left-hand + * iterator in forIn and forOf loops. + * + * @author Jessica Quynh Tran + */ + +'use strict'; + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ + +module.exports = { + create(context) { + + const msg = 'Use of `let` as the loop variable in a for-loop is ' + + 'not recommended. Please use `var` instead.'; + + /** + * Report function to test if the for-loop is declared using `let`. + */ + function testForLoop(node) { + if (node.init && node.init.kind === 'let') { + context.report(node.init, msg); + } + } + + /** + * Report function to test if the for-in or for-of loop + * is declared using `let`. + */ + function testForInOfLoop(node) { + if (node.left && node.left.kind === 'let') { + context.report(node.left, msg); + } + } + + return { + 'ForStatement': testForLoop, + 'ForInStatement': testForInOfLoop, + 'ForOfStatement': testForInOfLoop + }; + } +};