Step-by-step guide for resolving the "Uncaught ReferenceError" error in a for..in loop

Every time I attempt to utilize a for..of loop, I encounter a frustrating "ReferenceError" related to the iterator value.

Despite my efforts to convert the for...of loop into a for...in loop, the issue persists. I have a hunch that it may be connected to either the script tagged as a module, or potentially my utils.js file. However, even after removing them, the same error persists. This problem occurs specifically on Chrome 76 on Windows 10.

Below is the code in question:

<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, the loop would smoothly iterate over the array, but now it frustratingly throws this error. Any guidance or assistance on this matter would be sincerely appreciated!

Answer №1

When using scripts of type="module", strict mode is automatically applied. This results in a reference error when trying to use pti without declaring it beforehand.

To fix this issue, ensure that pti is defined. You can declare it as a variable in a for.. in loop, but be aware that you must declare it before starting a for...of loop, as the latter does not support variable definitions within the loop structure.

If you evaluate code outside of a module type script element, the error will not occur unless strict mode is explicitly invoked.

Answer №2

It appears that the declaration of pti may be missing.

You could consider modifying the code from

for (pti of points) console.log(pti);
to
for (let pti of points) console.log(pti);

Answer №3

For testing, you may want to experiment with this code using the Chrome developer tools

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

view the image description here

Make sure not to forget including the key pti

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I retrieve objects using the JSON function?

I need to design a function that returns objects like the following: function customFunction(){ new somewhere.api({ var fullAddress = ''; (process address using API) (return JSON data) })open(); } <input type= ...

An issue has been detected by Zone.js where the ZoneAwarePromise `(window|global).Promise` has been unexpectedly replaced

I have recently integrated the Angular2 quickstart code into my existing webpack setup, but I seem to be facing an issue where something is interfering with the promise from zone.js, resulting in an error. Based on my research on Stack Overflow, it appears ...

Activate modifications in a distinct column?

I've been exploring a solution to achieve a similar functionality where clicking or hovering on headings in a column brings up corresponding text in another column. My idea is to use list items with a carousel for this purpose, but I'm facing so ...

Here is how you can pass two callback functions to React.cloneElement:

Recently, I encountered an issue where one of the callbacks passed to a child component using React.cloneElement was always present while the other was undefined. Specifically, activeRow was consistently available but deactivateRow remained undefined. I ...

Nuxt: Encountered an unexpected < symbol

https://i.sstatic.net/MbM9f.png I've been working on a nuxt project where I'm currently in the process of creating a map component using Google Maps with the help of the plugin https://www.npmjs.com/package/vue2-google-maps. After installing the ...

Learn how to use Angular2 or TypeScript to display 'unsubscribe' and 'subscribe' text on a toggle button

I'm working on a toggle button that initially displays the word subscribe on the thumb. When the toggle is disabled, I want it to show unsubscribe instead. Can someone please help me achieve this functionality? Here's the code snippet: <md-s ...

Utilizing Vuex to Access a Component's Property in Vue

Utilizing Vuex in my app is integral for executing asynchronous tasks, such as logging a user into the application. Upon successful login and execution of axios.then(), I aim to notify the component from which I invoked this.$store.dispatch('login&apo ...

Issue encountered: ENOENT error - The specified file or directory does not exist. This error occurred while attempting to access a directory using the

I don't have much experience with nodejs or express, but I have an API running on http://localhost:3000. One of the endpoints triggers a function that uses the file system to read a file synchronously. However, when I send a post request using Postman ...

Transform Material UI Typography to css-in-js with styled-components

Can Material UI elements be converted to styled-components? <Container component="main" maxWidth="XS"> <Typography component="h1" variant="h5"> Sign in </Typography> I attempted this for typography but noticed that t ...

When provided with no input, the function will output true

I'm having trouble understanding this problem! I've implemented a basic jQuery validation that checks if an input field is empty when a button is clicked. http://fiddle.jshell.net/fyxP8/3/ I'm confused as to why the input field still retu ...

PHP count function providing incorrect results

Here are the details of two sets of data: $info = Array ( [@url] => url [@type] => image/jpeg [@expression] => full [@width] => 644 [@height] => 429 ) $total_count = count($info); // This returns 5, but I need it to be ...

Organizing multiple <image> tags into an array with Javascript - a beginner's guide!

My HTML file contains multiple images. When a user clicks on them, their IDs should be captured without any issues. I am looking for help with the following tasks: 1) Storing all clicked image IDs in an array For example: array = img01 ; array = img ...

Assign a Value to a Hidden Input Type When a User Submits a Form

I have a straightforward form set up in the following code. I am looking to add the value entered in the rm_accounts text box to the hidden page_confirm input value at the end of the URL. I hope that explanation is clear. In simple terms, if the user type ...

What is the best location to insert the code for toggling the text on a button?

I'm looking to update the button text upon clicking. When the button is clicked, the icon changes accordingly. I want the text to change from "Add to list" to "Added to list". I attempted to implement this functionality with some code, but I'm un ...

Utilizing getServerSideProps in the new app router (app/blah/page.tsx) for maximum functionality

I am a beginner in Next.js and I am currently experimenting with the new app router feature by placing my pages under app/.../page.tsx The code snippet provided works when using the page router (pages/blah.tsx) but encounters issues when used in app/blah/ ...

What is the best way to retrieve and obtain all relationship data as an array of objects using MySQL queries?

Assume there are three tables Primary table +----+------+---------------------+ | id | name | create_at | +----+------+---------------------+ | 1 | jack | 2023-04-26 22:01:37 | | 2 | tom | 2023-04-26 22:01:37 | +----+------+---------------- ...

The removal of the Lodash library from node modules is not occurring

In an effort to reduce bundle size, I made the decision to replace all lodash methods with core js methods in my Vuejs project. Despite attempting various npm uninstall commands such as: npm uninstall lodash npm uninstall lodash --save npm uninstall lodas ...

PHP Calculator - Displaying results in both the webpage and an Ajax popup for enhanced user experience

UPDATE - the issue was resolved by incorporating $('.popup-with-form').magnificPopup('open'); into the StateChanged function in the JavaScript. Many thanks to @Bollis for the assistance. The Initial Query: I have a basic calculator lo ...

The JSON data appears to be correct, yet it is not functioning properly when transmitted to X

I have a JSON object that has been validated using https://jsonlint.com/. However, I am encountering an error when trying to use this JSON with the Xero API as shown below. { "Type": "ACCREC", "Status": "AUTHORISED", "DueDate": "2021-12-11T14:24:0 ...

How can checkboxes be combined from two separate tables?

Within this interactive code example, you will find two tables containing checkboxes in each row. Upon clicking the To button, a dialog box will appear allowing you to select users or groups from a drop-down menu. The corresponding tables will then be dis ...