diff --git a/lib/coffeescript/nodes.js b/lib/coffeescript/nodes.js index fbec324d..8c4673fe 100644 --- a/lib/coffeescript/nodes.js +++ b/lib/coffeescript/nodes.js @@ -2043,7 +2043,7 @@ idx = del(o, 'index'); idxName = del(o, 'name'); namedIndex = idxName && idxName !== idx; - varPart = `${idx} = ${this.fromC}`; + varPart = known && !namedIndex ? `var ${idx} = ${this.fromC}` : `${idx} = ${this.fromC}`; if (this.toC !== this.toVar) { varPart += `, ${this.toC}`; } diff --git a/src/nodes.coffee b/src/nodes.coffee index 0d09caef..aa64c622 100644 --- a/src/nodes.coffee +++ b/src/nodes.coffee @@ -1353,7 +1353,11 @@ exports.Range = class Range extends Base idx = del o, 'index' idxName = del o, 'name' namedIndex = idxName and idxName isnt idx - varPart = "#{idx} = #{@fromC}" + varPart = + if known and not namedIndex + "var #{idx} = #{@fromC}" + else + "#{idx} = #{@fromC}" varPart += ", #{@toC}" if @toC isnt @toVar varPart += ", #{@step}" if @step isnt @stepVar [lt, gt] = ["#{idx} <#{@equals}", "#{idx} >#{@equals}"] diff --git a/test/ranges.coffee b/test/ranges.coffee index 7c0597a8..121286aa 100644 --- a/test/ranges.coffee +++ b/test/ranges.coffee @@ -195,3 +195,10 @@ test "#2047: from, to and step as variables", -> step = 0 r = (x for x in [b..a] by step) arrayEq r, [] + +test "#4884: Range not declaring var for the 'i'", -> + 'use strict' + [0..21].forEach (idx) -> + idx + 1 + + eq global.i, undefined