Permalink
Browse files

tools: avoid let in for loops

This adds a new ESLint tool to check for let
declarations within the for, forIn, forOf expressions.

Fixes: #9045
Ref: #8873
PR-URL: #9049
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Myles Borins <myles.borins@gmail.com>
Reviewed-By: Teddy Katz <teddy.katz@gmail.com>
Reviewed-By: Prince John Wesley <princejohnwesley@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information...
jessqt authored and jasnell committed Oct 12, 2016
1 parent 6eece77 commit 8ac29bd7c105c1d6e2a1d6e1eec9350a7f5a6109
Showing with 47 additions and 0 deletions.
  1. +1 −0 lib/.eslintrc
  2. +46 −0 tools/eslint-rules/no-let-in-for-declaration.js
@@ -2,3 +2,4 @@ rules:
# Custom rules in tools/eslint-rules
require-buffer: 2
buffer-constructor: 2
no-let-in-for-declaration: 2
@@ -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
};
}
};

0 comments on commit 8ac29bd

Please sign in to comment.