+ = does not work for me inside a Loop for of

1

I'm doing an ATM Javascript exercise and it works well, but I thought about improving it by validating the amount of money requested against the amount of money available in the ATM, so I did a "for of" cycle to get the sum available like this:

var caja =
[
  new Billete(50, 3),
  new Billete(20, 8),
  new Billete(10, 6),
  new Billete(5, 13),
];

var totalATM;

for( var bill of caja )
{
  totalATM += bill.valor * bill.cant;
}

consele(totalATM); //NaN

I do not understand why he does not do the summation and puts it in totalATM. Thanks.

    
asked by Renny Jose Galindez Fontecha 08.06.2017 в 23:51
source

2 answers

2

The += operator adds a value to the current content .

However, you do

var totalATM;

That is, you do not initialize the variable, so its content IS NOT A NUMBER , and you can not add anything .

Initialize the variable with 0 :

var totalATM = 0;
    
answered by 08.06.2017 / 23:57
source
2

The problem is simply that you do not initialize the variable totalATM , you can not add to the uninitialized variable, for that reason you get NAN (Not-A-Number).

as an example, if you initialize totalATM :

var totalATM = 0;
var billvalor = 2
var billcant = 3


for (i = 0; i < 5; i++) {
   totalATM += billvalor * billcant;
 }


console.log(totalATM);

If you do not initialize totalATM , you get NAN

var totalATM;
var billvalor = 2
var billcant = 3


for (i = 0; i < 5; i++) {
   totalATM += billvalor * billcant;
 }


console.log(totalATM); //NaN
    
answered by 09.06.2017 в 00:04