Skip to content

Scope Discrepancy in for Loop Variables #2

Description

@finitesimal

Python for loops create function-scoped variables, while transpiled JavaScript uses block-scoped let, causing reference errors when accessing loop variables post-loop.

Example:

def sum_range(n: int):
    total = 0
    for i in range(n):
        total = total + i
    return [total, i]  # Valid
function sum_range(n) {
    let total = 0;
    for (let i of Array.from({length: n}, (_, i) => i)) {
        total = (total + i);
    }
    return [total, i];  // ReferenceError
}

Proposed Fix:
Use var for loop variables accessed outside their loop, or implement static analysis to detect such cases.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions