Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: function returning NAN

Tags:

javascript

I'm working on a codecademy.com lesson with instructions to write the calculateTotal function below. When I click run, it's returning NaN. Anyone know what's wrong with the calculateTotal function as I wrote it that's making it return NaN. Note, I understand that NaN means not a number...

// runner times
var carlos = [9.6,10.6,11.2,10.3,11.5];
var liu = [10.6,11.2,9.4,12.3,10.1];
var timothy = [12.2,11.8,12.5,10.9,11.1];

// declare your function calculateTotal here
var calculateTotal = function(raceTimes){
    var totalTime; 
    for(i = 0; i < raceTimes.length; i++){
        totalTime += raceTimes[i]; 
        return totalTime; 
    }
};

var liuTotal = calculateTotal(liu);

console.log(liuTotal);

Note, many of the people answering this question have said that var totalTime has to be set to "O". However, in the next codecademy lessson, the author writes a function with totalTime not set to anything and it works

var calculateAverage = function (raceTimes) {
  var totalTime;
  for ( i = 0; i < raceTimes.length; i++ ) {
    totalTime = (totalTime || 0) + raceTimes[i];
  }
// assign variable averageTime
var averageTime = totalTime / raceTimes.length; 

  return averageTime;
};
like image 448
Leahcim Avatar asked Sep 15 '25 21:09

Leahcim


2 Answers

Two problems:

  1. totalTime is not defined -- adding something to an undefined results in NaN
  2. You are returning INSIDE your loop.

Fix:

var totalTime=0;
for(i = 0; i < raceTimes.length; i++){
    totalTime += raceTimes[i]; 
}
return totalTime; 
like image 119
Jamie Treworgy Avatar answered Sep 17 '25 13:09

Jamie Treworgy


You haven't initialized totalTime with a value. So it defaults to undefined. Therefore on each iteration, undefined is being added, yielding NaN.

like image 28
David G Avatar answered Sep 17 '25 13:09

David G