0

I'm currently working on a JavaScript problem, where I need to add an object to an empty array, 'expenses'. My addExpense function takes two arguments (description, amount), but I can only successfully add the 'amount' value to my empty 'expenses' array. The first argument, 'description' is declared but never read.

What is the reason for this distinction? Here is my code:

const account = {
    name: 'John Doe',
    expenses: [],
    addExpense: function (description, amount) {
        this.expenses.push({description: amount}) 
    }
    }

    account.addExpense('item', 15.00)

The above code will return

expenses: [ { description: 15 } ]

for the array.

Louis S
  • 11
  • 1
  • 3
    If you want to use the value of the `description` variable as the key, then you need to do `this.expenses.push({ [description]: amount })` so that JS will evaluate it. However, it feels a bit weird that you want to use a "free text" as property key: are you sure you're not trying to do `this.expenses.push({ description, amount })` instead? That's the shorthand for `{ description: description, amount: amount }` – Terry Feb 15 '21 at 13:38
  • Thank you for this explanation. I wasn't aware of the shorthand that you mentioned, but yes that's exactly what I was aiming for. – Louis S Feb 15 '21 at 13:44
  • You can see that when you declare `const account` you have keys named `name`, `expenses`, and `addExpense`. I suspect you don't have corresponding variables for them. Why do you assume that `description` will work differently? – VLAZ Feb 15 '21 at 13:44

0 Answers0