Zac Rissmiller
Zac Rissmiller

Reputation: 3

javaScript problems with NaN and += operator

first off thanks for taking the time. I'm working on an IBU calculator for beer making. Please see the comment below. parseB is a text input converted to a number I've seen the typeof ibuFinal is a number and the inBU[i] is also a number. why is it returning Nan?

var AAU=[]; 
var og=1.050;   
for(var i=0;i<6;i++){
    util[i]=(1.65*Math.pow(0.000125, og-1))*(1-Math.exp(-0.04*parseB[i]))/4.15;;                   
}

            function aau(){
                for(var i=0;i<6;i++){
                    AAU[i]=weight[i]*alpha[i];

                }
                return AAU;
            }

            function ibu(){

                var alphaAcid=aau();
                var inBU=[];
                var ibuFinal;

                for(var i=0;i,alphaAcid.length;i++){

                    inBU[i]=alphaAcid[i]*util[i]*75/batchSize;

                    ibuFinal+=inBU[i];//returns NaN for some reason!!
                }

                alert(ibuFinal);
            }
            ibu();

Upvotes: 0

Views: 270

Answers (1)

apsillers
apsillers

Reputation: 115940

You never define ibuFinal, so it's undefined.

The type-coercion in JavaScript's addition works out that undefined + 1 (or any number) is NaN. (In EMCAScript terms, ToNumber(undefined) is NaN, and NaN plus anything is NaN.)

Make sure you initialize ibuFinal to zero: var ibuFinal = 0;

Upvotes: 1

Related Questions