Skip to content

Scope Discrepancy in for Loop Variables #2

@finitesimal

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.

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