0

Im building a bankAccount program and trying to add my DDs into the global var, but as I create new objects from my constructor function then add them into bankAccount it only shows the last created dd?

What im trying to do is push all DD into bankAccount..

Code is below

// Created my bankAccount with the value of 0
var bankAccount = {};

// Object constructor to created direct debit with name and cost
function DirectDebit(name, cost) {
  this.name = name;
  this.cost = cost;
}

// Creating a new DD for my phone
var phone = new DirectDebit("Phone ", 20);
var car = new DirectDebit("Car ", 250);

function addToBank (dd) {
    bankAccount = dd
}

addToBank(phone)
addToBank(car)

console.log(bankAccount);

this outputs:

DirectDebit { name: 'Car ', cost: 250 }
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Kingsamama
  • 33
  • 6
  • 2
    Sounds like you want an array of dd objects? Your variable is storing only a single one. – Bergi Jan 02 '20 at 12:43
  • Yes thank you, changed the bankAccount to an array and addToBank method is pushing them so they can be stored. Cheers! – Kingsamama Jan 02 '20 at 12:48

1 Answers1

1

Create bankAccount as an array and push the data in the array rather than setting it.

var bankAccount = [];
function addToBank (dd) {
    bankAccount.push(dd);
}
Nikhil Goyal
  • 1,945
  • 1
  • 9
  • 17
  • Thank you, that works. I can now see all the created DDs in the bankAccount array. Now to build the total cost :D! cheers – Kingsamama Jan 02 '20 at 12:47