JavaScript is acting buggy and throwing an error because it cannot access the variable 'r' before it has been

Utilizing THREE.js's raycaster, I successfully linked a mouse event to my 3D model in my development environment. However, when I built it using VUE.js and ran it in the production environment, I encountered an error: Uncaught ReferenceError: Cannot access 'r' before initialization.

The original code in that function:

raycast( raycaster, intersects ) {

        const geometry = this.geometry;
        const material = this.material;
        const matrixWorld = this.matrixWorld;
                
                ...

                const start = Math.max( 0, drawRange.start );
        const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
                
        for ( let i = start, il = end; i < il; i += 3 ) {}
}

The updated code in that function:

raycast(t, e) {
              const n = this.geometry
              , i = this.material
              , r = this.matrixWorld;
                
              ...
             
              // ERROR HERE
              // Uncaught ReferenceError: Cannot access 'r' before initialization
              for (let n = Math.max(0, r.start), r = Math.min(s.count, r.start + r.count); n < r; n += 3){}
}


I implemented some code similar to the one causing the error, and the exact error occurred:

      const a = {age: 10}
      for (let b = a.age, a = 11; b < a; b++ ) {
        console.log(a)
      }

Here is my code :

  mounted() {
    this.init3D();
    this.animate();
  },
  methods: {
    init3D() {

      // Your initialization code here

    },
    onMouseMove(event) {

      // Mouse move functionality

    }
}

To resolve the error, you may need to revise the code sections highlighted in the errors and ensure proper variable declaration and initialization.

enter image description here enter image description here

EXTRA:

I built using the command npm buildPro. Here is an excerpt from my package.json file:

  "scripts": {
    // List of scripts
  },
"dependencies": {
    // List of dependencies
  },

Apologies for any language barriers or confusing text.

Answer №1

It appears to be a scope problem.

To illustrate, let's break down the simple example you provided:

const a = {age: 10}
for (let b = a.age, a = 11; b < a; b++ ) {
  console.log(a)
}

Within the for loop, you initialize a variable "b" with the value of "a" (referencing the external "a = {age: 10}"), then declare a new variable with the same name ("a = 11").

However, due to JavaScript's Temporal Dead Zone (TDZ), the variables in the for loop are automatically declared before the loop itself, overshadowing any other variables with the same name outside the loop. This results in the error message

"ReferenceError: Cannot access 'a' before initialization"
.

This means that all variables inside your loop are declared by TDZ, but not initialized. When trying to assign "b" to "a.age", the inner "a" is already declared by TDZ, replacing the external "a = {age: 10}". Therefore, when attempting to set "b" to this new "a" which is only declared and not yet initialized.

===

Similarly, after examining the code in the second image you shared, I noticed the same issue: https://i.sstatic.net/mS9Ze.png

...

https://i.sstatic.net/DVQQ5.png

The reference to "r.start" is not pointing to the external "r = this.matrixWorld" but rather to the "r = math.min()" declared within the for loop.

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

Display and view .dwg files using Javascript, HTML, and Angular

Looking for a way to upload and preview .dwg format images on a page created using js/HTML/angularjs or Angular 2+? I've attempted to use a CAD viewer js library, but the lack of documentation has made it challenging. Has anyone successfully implement ...

Is it possible for an object in three.js to be both rotated and moved simultaneously?

Hello, thank you for your time. I'm trying to simultaneously move and rotate an object, but it seems to be behaving erratically. I've read that rotation can change the axis in some way. Is this true? Below is the code where I attempted to rotate ...

Uploading standard image when selecting a file

I have been searching and struggling to find a solution on how to automatically attach a default image when the user clicks "Choose File" using JavaScript or jQuery. My intention is that if the user forgets to attach an image, a default image URL will be ...

Adjust the size of the logo as the user scrolls

Currently, I am implementing a JavaScript feature that allows my logo to shrink when the user scrolls down and grow when they scroll up. To achieve this effect, I am utilizing the jQuery functions addClass and removeClass. However, I have encountered som ...

Center-align the content in Material UI Typography by using the variant attribute for the caption

I'm struggling to center the content of my Typography elements with default and caption variants using the align="center" property. The alignment doesn't seem to be working properly, especially for the variant as caption. Here is a snip ...

Using an external JavaScript script may encounter difficulties when loading pages with jQuery

Trying to utilize jQuery for loading html posts into the main html page and enabling external scripts to function on them. Utilizing a script (load.js) to load posts into the index.html page: $(document).ready(function () { $('#header').loa ...

Error encountered when applying filter function in AngularJS/JavaScript due to syntax issue

Encountering an issue with the filter method in AngularJS/Javascript. Below is the code snippet: var temp = []; $scope.mulImage = $scope.mulImage.filter((x, i) => { if(temp.indexOf(x.filename) < 0) { temp.push(x.filename); retur ...

What is the best way to remove a selected item from an array in Vuejs when it has been clicked

I'm having trouble with my splice() method in this simple To-Do app. I want to delete a specific task by clicking a button, but the solutions I've tried from Stack Overflow aren't working for me. The items do get deleted, but only the last o ...

Is there a way to redirect the user directly to the upload page without displaying the response?

Recently, I came across this code snippet that adds a progress bar to an upload form. Currently, the code displays the response from the upload page below the form. However, my goal is to redirect the user to the upload page so they can view the response t ...

Tips for integrating JavaScript into a Django project

I am currently developing a Django application that I want to make highly flexible and reusable. As I work on this project, I find myself thinking about the best practices for ensuring that my app can seamlessly integrate into larger projects where jQuer ...

Capturing HTML form values and storing them in my JavaScript data object

I have a JS object with preset data as shown below in the variable var json. I am trying to create a simple HTML web form where I want the user inputs to be added as a new data set within my initial JS object. Here is the initial JS object data. The submi ...

using jQuery to retrieve JSON data containing nested arrays

I'm currently working with a music player that requires fetching JSON values dynamically from a page. The issue I am facing is the format of the JSON, which looks something like this: {"audios":[{"audio":{"name":"makakyala","audio":{"audio":{"url":"/ ...

Ways to run evaluations on 'private' functions within an angular service using Karma and Jasmine

In my Angular application, I have a BracketService that consists of various functions for comparing weights and creating brackets based on weight groups. The service includes functions like compareByWeight, filterWeightGroup, and createBracketsByWeightGrou ...

How can I create a redirect link in HTML that opens in a new window

I have a HTML page where I need to redirect to the next page. <a href="www.facebook.com" target="_blank">www.facebbok.com</a> Currently, it is redirecting to localhost:9000/dashboard/www.facebook.com But I only want to redirect to www.facebo ...

How can the Angular Js framework be utilized to create a pop-up feature in combination with Bootstrap?

I'm currently working on a website using AngularJS and Bootstrap. When the site is loading, I make a server call to fetch some data. This process takes some time, and during this interval, I want to display a pop-up message indicating that the user s ...

Static IP Address Proxy for Inbound Traffic in App Engine and Cloud Environments

Many cloud platforms, including App Engine, utilize a diverse set of IP addresses, posing challenges for users with firewall restrictions. We have clients interested in our services but they are limited to sending requests to specific IP addresses. Is th ...

Dynamic route fails to return value for ID search

Currently, I am testing by creating an array of users containing their respective IDs and names. There is also a button that triggers an onclick function to add the element's ID to the page's URL in order to establish a dynamic route. However, wh ...

Guide to Creating a Pop Up Image Display with Bootstrap

Can someone help me achieve the same functionality as the Fiddle linked below? http://jsfiddle.net/6CR2H/1/ I have tried to replicate it by including both external files, but the image is not displaying as a pop-up when clicked. <link href="http:// ...

The animation glitches out when attempting to update the color of the imported model

I'm facing an issue with a Blender model that has animation. After uploading it to the site, the animation works perfectly. However, I'm trying to change the body color of the model, and when I attempt to do so, the body stops animating and becom ...

Tips for setting up a foreign key in MongoDB using Mongoose

I have a basic "table" for users, each with a unique username, an email, and a password. In the file users.js: const mongoose = require('mongoose') const UserSchema = new mongoose.Schema( { username: { type: String, required: true, u ...