Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected NaN output after typeof var displays expected numer type

Tags:

javascript

nan

Getting an unexpected NaN on an Exercise in Eloquent Javascript chapter 4, but the error is not obvious enough for me to pick up on it. Would someone mind taking a look and pointing out my error?

/*
Write a range function that takes two arguments, start and end, and returns an array containing all the numbers from start up to (and including) end.
*/
var numRng = [];
function range( start, end ) {
  //var numRng = [];
  cntr = ( end - start );
  for ( i = 0; i <= cntr; i++ ) {
    numRng.push( start );
    start++;
  } // end FOR
  //return numRng;
} // end FUNC range

range( 1, 10 );
/*for ( i = 0; i < numRng.length; i++ ) {
  console.log( 'Array element ' + numRng.indexOf( 1 + i ) + ' contains range value: ' + numRng[i] );
}*/

/*
Next, write a sum function that takes an array of numbers and returns the sum of these numbers. Run the previous program and see whether it does indeed return 55.
*/
var total = 0;
function sum( numRng ) {
  //var total = 0;
  for ( i = 0; i <= numRng.length; i++ ) {
    //console.log( total );
    total += numRng[i];
    //console.log( total );      
  } // end FOR
  console.log( typeof total );
  console.log( total );      
} // end FUNC range

sum( numRng );
console.log( 'Total sum of all element values held by array numRng is: ' + total );

And here is the Firebug output, displaying that typeof total after the for loop in func sum is indeed number but is then output as NaN.

var numRng = []; // seem to require global var ...nt values held by array numRng is: ' + total ); 
number
NaN
Total sum of all element values held by array numRng is: NaN

Any help appreciated.

like image 401
scriptz Avatar asked Feb 28 '17 18:02

scriptz


1 Answers

The problem is here

for ( i = 0; i <= numRng.length; i++ )
                ^

numRng[numRng.length] => undefined
I corrected the code below

var numRng = [];
function range( start, end ) {
  //var numRng = [];
  cntr = ( end - start );
  for ( i = 0; i <= cntr; i++ ) {
    numRng.push( start );
    start++;
  } 
} 

range( 1, 10 );


var total = 0;
function sum( numRng ) {
  for ( i = 0; i < numRng.length; i++ ) {
    total += numRng[i]; 
  }
  console.log( typeof total );
  console.log( total );      
}
sum( numRng );
console.log( 'Total sum of all element values held by array numRng is: ' + total );
like image 196
Sagar V Avatar answered Sep 16 '22 15:09

Sagar V