Ways to Resolve the Error "Uncaught TypeError: Cannot Assign Value to Undefined Property '0'"

After experimenting with the code below, I discovered that when arrays (bill, tipValue, totalAmmount) are declared within the object method, I encounter a "cannot set property '0' undefined" error. However, if the same arrays are declared outside the object, I achieve the expected result.

Code throwing exception:

var john = {
    bill: [124, 48, 268, 180, 42],
    tipValue: [],
    totalAmmount: [],
    calcTip() {
        this.bill.forEach(function (ele, i) {
            this.tipValue[i] = innercalc(ele);
            this.totalAmmount[i] = this.tipValue[i] + ele;
        }); //not working code

        function innercalc(value) {
            if (value < 50)
                return value * 0.2;
            else if (value > 50 && value < 200)
                return value * 0.15;
            else if (value > 200)
                return value * 0.1;
        }
    }
}

john.calcTip();
console.log(john.tipValue);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
   
    <script src="codingchallange5.js"></script>

</body>
</html>

Uncaught Exception: Cannot set Property '0' of undefined

Working code snippet:

var tipValue = [];
var totalAmmount = [];
var john = {
    bill: [124, 48, 268, 180, 42],
    
    calcTip() {
        this.bill.forEach(function (ele, i) {
            tipValue[i] = innercalc(ele);
            totalAmmount[i] = tipValue[i] + ele;
        }); //working code

        function innercalc(value) {
            if (value < 50)
                return value * 0.2;
            else if (value > 50 && value < 200)
                return value * 0.15;
            else if (value > 200)
                return value * 0.1;
        }
    }
}

john.calcTip();
console.log(tipValue);
<!DOCTYPE html>
<html lang="en">>
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title> 
</head>
<body>
    
    <script src="codingchallange5.js"></script>

</body></html>

Answer №1

Utilize arrow functions to maintain the integrity of this and ensure everything runs smoothly as expected:

var john = {
  bill: [124, 48, 268, 180, 42],
  tipValue: [],
  totalAmmount: [],
  calcTip() {

    this.bill.forEach((ele, i) => { // implement arrow function here
      this.tipValue[i] = innercalc(ele);
      this.totalAmmount[i] = this.tipValue[i] + ele;
    });

    function innercalc(value) {
      if (value < 50)
        return value * 0.2;
      else if (value > 50 && value < 200)
        return value * 0.15;
      else if (value > 200)
        return value * 0.1;
    }

  }
}

john.calcTip();
console.log(john.tipValue);

As per MDN: Arrow function expression provides a concise syntax compared to regular function expressions, while maintaining its own bindings to the this, arguments, super, or new.target keywords.

Answer №2

When utilizing this in the function forEach(), it defaults to being undefined if no reference argument is passed. It is crucial to provide a reference to john when using forEach()!

    this.bill.forEach(function (ele, i) {
            this.tipValue[i] = innercalc(ele);
            this.totalAmmount[i] = this.tipValue[i] + ele;
        }, this);

array.forEach(function(currentValue, index, arr), thisValue)

thisValue:

  • Optional. A value passed to the function to serve as its "this" value.
  • If left empty, it will default to "undefined" as the "this" value.

JavaScript Array forEach() Method

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

The request for data:image/png;base64,{{image}} could not be processed due to an invalid URL

I am facing an issue with converting image data that I receive from the server using Angular.js for use in ionic-framework. Here is the code snippet I have been working with: $http.post(link, { token: token, reservationCode: reservatio ...

Adding a class to a navigation item based on the route path can be achieved by following

I am currently working on a Vue.js project and I have a navigation component with multiple router-links within li elements like the example below <li class="m-menu__item m-menu__item--active" aria-haspopup="true" id="da ...

Struggling to arrange a list of numbers in ascending order within an array

Hello everyone, I'm a newbie here and I'm not sure if I'm posting this correctly. I need some help sorting the population of states from smallest to largest based on data from a separate file. Currently, the program is only displaying the st ...

Unable to adjust the size of a DIV with a button click in Vue3

I am having trouble resizing a DIV block in Vue3. Whenever I click the button, I receive an error message saying "Cannot read properties of undefined (reading 'style')". I know there is an issue with the JS part of the code, but I'm not sure ...

What is the best way to avoid repeated guesses in a number guessing game?

I've implemented an array named 'tries' to keep track of the numbers guessed by the user. Once the user correctly guesses the number, the total number of tries and the guessed numbers are displayed. How can I prevent the user from guessing a ...

Iterate through a foreach loop and transfer items from the loop into a fresh multi-dimensional array

Currently, I have a foreach loop set up to iterate over an array and extract specific information from it. My goal is to store this extracted data in a separate empty array. While my existing code somewhat achieves this, there are some issues with the stru ...

Encountering a "dependency resolution error" while deploying a React application with Parcel on Heroku

I've developed a compact application and I'm in the process of deploying it to Heroku. However, I keep encountering an error stating: '@emotion/is-prop-valid' dependency cannot be resolved. It's worth mentioning that this project d ...

The command is failing to include functionality with the yarg npm package

I have been attempting to incorporate a command using yargs, however, after executing my code, the command does not seem to be added successfully. Below is the snippet of what I am attempting: const yargs = require('yargs') //create add command ...

Is there a way to include a function for sorting an array and another function to reverse the array in one program?

For the task I was given, I had to create an orderedArray method and a reverseArray method. I completed the task, however, I used a static void which caused only the first method to work while the second method did not. The ordering method functioned corr ...

How can I make sure addEventListener only responds to numbers and not images?

Currently, I am facing a dilemma with implementing a button that features an image on it and needs to be placed within another div. Despite successfully achieving this, I am struggling to comprehend the JavaScript code outlined in a tutorial I followed. Th ...

Securing Routes with Firebase User Authentication in ReactJS

Currently, I am encountering an issue with the auth.onAuthStateChanged function in my Firebase user authentication service integrated with ReactJS. The function fires after the component has already been rendered, causing problems with redirecting users to ...

Access information through token-based verification

Just starting out in this area of development, a colleague shared some information with me on how to retrieve the database. I'm feeling a bit lost as to what to do next. curl -X GET -H "Authorization: Token token=xxxxxxxxxxxxxxxxxxxxxxxxx" "https://w ...

Pairing TMDb genre IDs and their respective names using JavaScript within the Ember.js framework

If you've ever worked with the TMDb (The Movie Database) api for movies, you might have encountered this issue. I am struggling to display the genre names for each movie shown. My goal is to replace the numbers in genre_ids from the movies api with th ...

Why is it that this specific ASP.NET + jQuery + JavaScript custom MVC setup isn't displaying any content?

After attempting to incorporate this JavaScript MVC example from into an ASP.NET page, I am facing issues as a beginner with jQuery. Nothing seems to show up on the page, and I'm unsure why. Update: I have included the missing HTML listbox, but now ...

Assigning values from one row to another within a numpy array

If I have a list of names in a numpy array like this: array(['Ana', 'Charlie', 'Andrew'], dtype=object) I am looking to create pairs of all possible combinations from the names in the array. The desired output would be: [& ...

Tips for streaming a partially generated video file in a web browser

My current issue involves a program that generates a video in a specific file format, and I want to display this video file in popular browsers like Firefox, Chrome, or any other browser using an HTML5 tag. The problem arises when the video file is only 5 ...

Automatically submitting Ajax form upon loading the page

I am attempting to use ajax to automatically submit a form to a database upon page load. The form and php code work perfectly when manually submitted, but for some reason, the ajax function does not trigger. Despite checking the console for errors and con ...

Sending the `<path>` wrapped in quotes to `<SvgIcon>` is resulting in the SVG not rendering

When I try to use the Material-UI's SvgIcon component, the <path> element is surrounded by quotes, which is preventing the SVG from rendering properly. https://i.stack.imgur.com/InDRt.png I'm currently working in Storybook within an MDX f ...

What is the fate of the code that comes after executing history. push in React?

My go-to for routing is typically the Redirect component. It's straightforward since you just need to return the Redirect component when needed. However, I'm a bit lost when it comes to using history objects. In my code base, after pushing a rout ...

Attempting to incorporate country flags into the Currency Converter feature

www.womenpalace.com hello :) i'm looking to customize my Currency Converter with Flags images. this is the code for the converter: <select id ="currencies" class="currencies" name="currencies" data-default-shop-currency="{{ shop.currency }}" ...