Search code examples
javascriptarraysobjectreferenceerror

How to fix "Uncaught ReferenceError" in a for..in loop


When I'm using a for..of loop, the iterator value throws a "ReferenceError" when I try to run it.

I've tried changing the for...of loop into a for...in loop, but to no avail. I suspect that it has something to do with the script tagged as a module, or it might be my utils.js file, but I removed them and I still get the same server. I'm getting this error on Chrome 76 on Windows 10.

Here's the code:

<body>
    <canvas id="canvas" width="800" height="600">
        Bruh. are you using IE?!
    </canvas>
    <script type="module">
        import { Mouse, Screen } from "./utils.js"

        let attractionForce = 1;
        let friction = 0.99;

        let canvas = document.getElementById("canvas");
        let ctx = canvas.getContext("2d");
        //let mouse = new Mouse(canvas);
        const PI_2 = Math.PI * 2;

        var points = Array.from({ length: 1000 }, () => ({
            x: Math.random() * 800,
            y: Math.random() * 600,
            dx: (Math.random() - 0.5),
            dy: (Math.random() - 0.5),
        }));

        for (pti of points) console.log(pti); << Uncaught ReferenceError: pti is not defined
    </script>
</body>

Normally, it would just iterate over the loop, but now it's throwing an error. Any help would be greatly appreciated!


Solution

  • Scripts of type="module" use strict mode automatically. Hence, because pti is not defined before use, you get the reference error.

    Obviously the cure is to make sure pti is defined. You can declare it as a variable in a for.. in loop, but you have to declare it before starting a for...of loop because the syntax of the latter does not support variable definitions in the control structure.

    Code evaluation outside a module type script element won't reproduce the error without invoking strict mode.