skip to Main Content

There is something that I couldn’t understand. I have the following code, which its purpose is to get the total of the two arrays.

let r1;
let r2;
let total;

function totalSum(arr_1, arr_2) {
  for (let i = 0; i < arr_1.length; i++) r1 += arr_1[i];
  for (let j = 0; j < arr_2.length; j++) r2 += arr_2[j];
  total = r1 + r2;
  return total;
}

let arr_1 = [3, 5, 22, 5, 7, 2, 45, 75, 89, 21, 2]; // --> 276
let arr_2 = [9, 2, 42, 55, 71, 22, 4, 5, 90, 25, 26]; // --> 351

totalSum(arr_1, arr_2);

console.log(`total=${total} r1=${r1} r2=${r2}`);
  • When I tried to print the result it printed "NaN" for all variables (r1, r2, and total).
  • However, after I initialized the r1 and r2. It returned the desired outcome.
let r1 = 0;
let r2 = 0;
let total;

My question is, why do the r1 and r2 couldn’t get the sum of the arrays without the initialization? While the variable total could get the result of r1 and r2 even though it wasn’t initialized?

3

Answers


  1. when you define a variable without assigning the value, its value by default is "undefined". in this case, you’re trying to do maths with number and undefined, which will convert to NaN

    Login or Signup to reply.
  2. Try to find the values in arr_1 and arr_2. If they don’t have numbers, you’ll get unusual answers. In this case, they are undefined, and anything undefined is converted to NaN if any operation is applied to it.

    Login or Signup to reply.
  3. The answer is because you are adding r1 += arr_1[i]; which means undefined+=arr_1[i] for the first time. since undefined cannot be added with, it returns NaN for each and every addition done from first to last. But in total case, you are assigning the value total=r1+r2 so in that case even if total was undefined it was reassigned another value, which was r1 + r2. So in short, you cannot add to an undefined value but you can assign another variable to an undefined value. Hope it answers the question.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search