Managing functions within objects: A guide

I'm having an issue with handling a simple personalAccount object in JavaScript. I have defined some functions within the object keys, but when I try to display the output of my accountBalance function using console.log, it doesn't show the expected result.

Within the accountSummary key, I am calculating the difference between totalIncome and totalExpense to get the desired output, but instead of getting the correct result, I am seeing NaN (Not a Number) in the terminal.

`

const personAccount = {
    firstName: 'Prashant',
    lastName: 'Singh',
    incomes: [20000, 30000, 40000],
    expenses: [],
    totalIncome: function() {
        return this.incomes.reduce((acc, curr) => acc + curr, 0);
    },
    totalExpense: function() {
        return this.expenses.reduce((acc, curr) => acc + curr, 0);
    },
    accountInfo: function () {
        return `First Name: ${this.firstName}, Last Name: ${this.lastName}, Total Income: ${this.totalIncome()}, Total Expense: ${this.totalExpense()}, Account Balance: ${this.totalIncome() - this.totalExpense()}`
    },
    addIncome: function (income) {
        this.incomes.push(income);
        return this.incomes;
    },
    addExpense: function (expenses){
        this.expenses.push(expenses);
        return this.expenses;
    },
    accountBalance: function () {
        return this.totalIncome() - this.totalExpense();
    },
    accountSummary: function () {
        return `First Name: ${this.firstName}, Last Name: ${this.lastName}, Balance: ${this.accountBalance()}`
    }
}

`

Answer №1

Your code appears to be functioning correctly, but the key lies in how you are accessing it. Take a look at this demo for a better understanding and try to identify the underlying issue.

const userFinance = {
  income: [25000, 35000, 45000],
  expenses: [],
  totalIncome: function() {
    return this.income.reduce((acc, curr) => acc + curr,0);
  },
  totalExpense: function() {
    return this.expenses.reduce((acc, curr) => acc + curr,0);
  },
  balance: function () {
    return this.totalIncome() - this.totalExpense();
  }
};

console.log(userFinance.balance());

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

What is the best way to extract a number from a string in JavaScript?

There are instances in HTML files where a <p> tag displays the price of a product, such as ""1,200,000 Dollar"". When a user adds this product to their cart, I want the webpage to show the total price in the cart. In JavaScript, I aim to e ...

incorporating a personalized HTMLElement using Typescript

Hey there! I'm fairly new to using Angular and could use some help. I'm trying to insert a custom HTML element onto a page when a button is clicked, but I'm struggling to figure it out. Here are my HTML and TypeScript files: TypeScript Fil ...

What is the process for retrieving DOM elements and JavaScript variables using PHP?

I am currently developing a PHP script that will dynamically generate tables in MySQL based on the user's input for the number of columns and column names. However, I have encountered some challenges when trying to access DOM elements and JavaScript v ...

The aspect ratio of Threejs sprites is appearing distorted

I'm facing an issue with rendering two objects in an Orthographic camera using Three.js. The objects are not rendering correctly and I'm unsure of the reason behind it. The expected look of the two images is as follows: https://i.sstatic.net/hQ ...

Comparing vue.component to using import statements inside a component

After setting up a vue2 library using vue-cli, I have numerous components included in the index.ts file as shown below: import MyComponent1 from './components/MyComponent1.vue'; import MyComponent2 from './components/MyComponent2.vue'; ...

Tips for troubleshooting 'npm ERR! 403: The requested package version is not permitted by your security policy. Typically, this issue arises when you or one of your dependencies are attempting to access a restricted package version.'

Currently, I am in the process of setting up a Jenkins and a private npm repository called Sonatype Nexus. I am encountering an error when attempting to publish to the repository within a Jenkins build pipeline. + npm publish --registry https://<my-priv ...

Is there a way to display the drawer component from Material UI only on specific routes using routing in ReactJS with MaterialUI?

In my react project, I have implemented a material-UI drawer component. The issue I am facing is that the drawer component contains the page content within itself. Previously, I managed to integrate routes using react-router-dom with the drawer. My current ...

Segmentation Fault Issue Caused by Basic C++ Encryption Function for Character Arrays

Encountering the usual issues with pointers once again. My goal is to create a basic "encryption/decryption" function for char arrays. I am well aware that strings can be used for this purpose, but my aim is to enhance my understanding of pointers and util ...

Connect a datetime-local typed input to a Date attribute in Angular 2

Can a property of type Date in a component be bound to an HTML5 input with the type attribute set as datetime-local? For example, I have a component with the following property: public filterDateFrom: Date; And in my template, I am trying to bind this p ...

Encountered an error message stating "This dependency was not found" after installing a package using npm

I recently added a package called htmldiff to my Vue project using the npm install command. The next step was to try importing the package into one of my components. import { diff } from 'htmldiff'; // note that the package does not use default ...

What is the process for attaching text or labels to an object, similar to applying decals?

Check out this website: On this site, you can create text, add it to objects like a decal, and then click "Ok" to confirm. Is there a way to make this effect visible on the design? Many thanks in advance! ...

Why does TypeScript trigger an ESLint error when using `extend` on a template string?

I am looking to create a TrimStart type in the following way: type TrimStart<T extends string> = T extends ` ${infer Rest}` ? TrimStart<Rest> : T; type TT = TrimStart<' Vue React Angular'>; // 'Vue React Angular' H ...

JavaScript along with Mongoose executes the for-loop prior to carrying out the .find operation inside

My partner and I are trying to calculate the average rating for each movie in our MongoDB database. We have two collections: Movie and Rating. Our approach involves retrieving all the movies first, then looping through each movie to find its corresponding ...

Converting a list into a two-dimensional array using Python: a step-by-step guide

Currently, I am utilizing function X which requires input values in the form of np.ndarray, shape=(num_pairs, 2), dtype=int. However, I only have a list as follows: l=[a,b] and I would like to use this list as input for the function X. Upon attempting to ...

Identifying added elements that respond to link hover effects

I've been working on a project where I'm trying to replace the default browser cursor with an SVG one using jQuery. Everything seems to be working smoothly, except for changing the cursor when it hovers over links - nothing I've tried so far ...

The act of searching for items within a table is interfering with the pagination of the table

My table divides its items into 20 lines each and includes a search input above it to filter items based on written words. Each tool works fine independently - I can easily navigate through multiple pages when there are more than 20 items, and I can find s ...

Can you explain the variance between Facebook HTML and traditional HTML5?

A client has recently requested my services to create a basic Facebook page for them. Since I am not well-versed in the realm of Facebook webpages, can you guide me towards the right sources to answer the following question: What distinguishes HTML5 from ...

Choose particular elements within an array

I am working with an array that contains certain lines I need to highlight, specifically A and B: [0] A1 [1] a line I don't need [2] B1 [3] another line I'm not interested in [4] A2 [5] yet another line I want to ignore [6] B2 [7] something else ...

Routes for Express are throwing a 500 internal server error

My server is unable to locate the APIs that I have created in the API directory, which is resulting in a 500 internal server error. I have thoroughly checked routes.js and everything appears to be correct. Additionally, I have an error.js file for handlin ...

How can you modify the encapsulation of a third-party component in an Angular application?

Utilizing AngularElements with native encapsulation allows bs4 components to be used in a bs3 project. For example: @Component({ selector: 'app-my-button', templateUrl: './my-button.component.html', encapsulation: ViewEncapsulati ...