Skip to content

Commit 87285ed

Browse files
jalafelMyles Borins
authored and
Myles Borins
committedNov 11, 2016
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 <[email protected]> Reviewed-By: Myles Borins <[email protected]> Reviewed-By: Teddy Katz <[email protected]> Reviewed-By: Prince John Wesley <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 0f1a22d commit 87285ed

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
 

‎lib/.eslintrc

+1
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ rules:
22
# Custom rules in tools/eslint-rules
33
require-buffer: 2
44
buffer-constructor: 2
5+
no-let-in-for-declaration: 2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* @fileoverview Prohibit the use of `let` as the loop variable
3+
* in the initialization of for, and the left-hand
4+
* iterator in forIn and forOf loops.
5+
*
6+
* @author Jessica Quynh Tran
7+
*/
8+
9+
'use strict';
10+
11+
//------------------------------------------------------------------------------
12+
// Rule Definition
13+
//------------------------------------------------------------------------------
14+
15+
module.exports = {
16+
create(context) {
17+
18+
const msg = 'Use of `let` as the loop variable in a for-loop is ' +
19+
'not recommended. Please use `var` instead.';
20+
21+
/**
22+
* Report function to test if the for-loop is declared using `let`.
23+
*/
24+
function testForLoop(node) {
25+
if (node.init && node.init.kind === 'let') {
26+
context.report(node.init, msg);
27+
}
28+
}
29+
30+
/**
31+
* Report function to test if the for-in or for-of loop
32+
* is declared using `let`.
33+
*/
34+
function testForInOfLoop(node) {
35+
if (node.left && node.left.kind === 'let') {
36+
context.report(node.left, msg);
37+
}
38+
}
39+
40+
return {
41+
'ForStatement': testForLoop,
42+
'ForInStatement': testForInOfLoop,
43+
'ForOfStatement': testForInOfLoop
44+
};
45+
}
46+
};

0 commit comments

Comments
 (0)
Please sign in to comment.