JSK
JSK

Reputation: 1276

why I'm getting Not-A-Number instead of a Value returned by my function

I'm trying to do some simple calculations but my function still return a NaN(Not-A-Number).
According to MDN NaN means not a number so I tried to converted to a number with Number() but still return the same thing , here is the code :

function capPow() {
  var arr = [];
  for (var i = 1 ; i <= 100 ; i++) {
    var result = Math.pow(i, 2);
        arr.push(result);
  }

  for (var j = 0 ; i < arr.length ; i++) {
    var result2 =+ arr[i];
  }
  var finfin = Math.pow(result2, 2);
  var ending = finfin - result2;

  return Number(ending);
}

console.log(capPow());

result :

NaN

Upvotes: 1

Views: 63

Answers (2)

Compass
Compass

Reputation: 5937

There's a few errors, so I'll go step by step.

This for loop is the source of the headache.

for (var j = 0 ; i < arr.length ; i++) {
    var result2 =+ arr[i];
}

You declared var j and then use i for < and ++ comparisons, and then get the index from i again. There's also a reversal of the += method. In addition, result2 goes out of scope over and over, so even fixing it to += doesn't help since result2 doesn't exist outside the for loop. You need to declare it outside the for loop in order for it to stay in existence for when you calculate finfin.

Should be:

var result2 = 0;
for (var j = 0 ; j < arr.length ; j++) {
    result2 += arr[j];
}

When in doubt, log everything. A console.log(result2) before var finfin will show you that result2 was not defined the entire time, and a console.log(j) will show you the loop was not being entered at all.

Upvotes: 4

rakhmanoff
rakhmanoff

Reputation: 369

Possibly, you have a typo:

var result2 += arr[i];

Also you should define you result2 outside the for statement

Also you have couple errors. This is updated jsfiddle with fixes: http://jsfiddle.net/rm3cpk5e/

Upvotes: 0

Related Questions