-1

I seem to be getting a NaN error as the result in my JavaScript code.

I'm pretty new to this, would appreciate any help.

Solved by giving value to the total var.

5 Answers5

2

There are a couple of problems:

  • You should use parseFloat instead of using strings.
  • You should initialize total (this is what causes the nan)
  • You should initialize arrays properly.

function tax() {
    var price = new Array(10);
    var quant = new Array(10);
    var taxam = 18;
    var total = 0;
    for(i=0;i<10;i++) {
        quant[i] = parseFloat(prompt("Insert Quantity: "));
        price[i] = parseFloat(prompt("Insert Price: "));
    }
    for(i=0;i<10;i++) {
        total += price[i] * quant[i];
    }
    total = total * (taxam / 100);
    alert(total);
}
simonzack
  • 19,729
  • 13
  • 73
  • 118
  • 1
    Well, `"10" * "10"` is still `100`, multiplying numeric strings make perfect sense. – adeneo Dec 16 '15 at 08:15
  • @adeneo Thanks that's a js quirk I wasn't aware of, I think he's problem is not initializing `total`. Do you happen to know if this quirk exists in strict mode? – simonzack Dec 16 '15 at 08:18
  • @Normal_Dude_LearnsCode No problems you can accept it if it helped. – simonzack Dec 16 '15 at 08:23
1

I guess with this var price = [10] you were trying to create an array with 10 numbers, but that is not the way it works in Javascript var price = [10] will give you an array with 10 at the 0th position. The only other tweak I would make there is make var price = [1,2,3,4,5,6,7,8,9,10] to actually achieve what you set out for initally

Ade
  • 181
  • 1
  • 1
  • 14
0

First of all, JavaScript is not Java ;)

You seem to try to initialize your arrays with a length of 10. This works in Java but in Javascript an array is dynamic and writing :

myArray = [10];

will just set the value 10 in the first index of the array.

Then, as you prompt the user to input numbers, the numbers will be interpreted as a string. So it would be good to cast it to a number before working with it. To cast it :

var value = '10000';
valueAsInt = parseFloat('10000',10);
//or simply 
valueAsInt = +value;

Now we come to your problem, as total is not initialised, the first affectation will be

undefined += n;

this will give a NaN.

So just initialise total before using it :

var total = 0;
ylerjen
  • 4,109
  • 2
  • 25
  • 43
0

you have to initialize total variable first because it is undefined initially

var total = 0;
ojus kulkarni
  • 1,877
  • 3
  • 25
  • 41
-1

You have to parse the String variables to a Number:

function tax() {

var price = [10];
var quant = [10];
var taxam = 18;
var total = 0;

 for(i=0;i<10;i++) {

    quant[i] = Number(prompt("Insert Quantity: "));

    price[i] = Number(prompt("Insert Price: "));

    }

for(i=0;i<10;i++) {

total += price[i] * quant[i];

 }

total = total * (taxam / 100);

alert(total);


}
tax()
Daniel 976034
  • 189
  • 1
  • 1
  • 18