Home > database >  How to handle functions inside an Objects
How to handle functions inside an Objects

Time:10-26

I am trying to handle an simple personalAccount object in javascript. I have created some function inside objects key but when i'm trying to console my accountBalance funtion it not showing desire output.

I'm trying income and expense data inside accountSummary key it should me (totalIncome - totalExpense) = desire output, but it gives NaN in my 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()}`
    }
}

`

CodePudding user response:

Your code should work fine, It's all about how you are accessing it. Here is the working demo, Kindly review and try to find the root cause.

const personAccount = {
  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);
  },
  accountBalance: function () {
    return this.totalIncome() - this.totalExpense();
  }
};

console.log(personAccount.accountBalance());

  • Related