0

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?

user3840170
  • 26,597
  • 4
  • 30
  • 62
  • 1
    try `console.log(undefined+1)` . initalize without value gives undefined. total works without initilizng because you are not adding but reassigning a value – cmgchess Apr 30 '23 at 07:31
  • Just an FYI you could remove one of the loops (assuming you know they're both the same size) and just do `for(let i = 0; i < arr1.length; i++) { total += arr1[i] + arr2[i]; }` – Jhecht Apr 30 '23 at 07:40
  • 2
    Because with `r1 += ...` you are doing `undefined + 1` in the very first iteration and that's `NaN`. When you assign `total = r1 + r2` you are assiging the result of `r1 +r2` to total and replacing any prior value – derpirscher Apr 30 '23 at 07:59

2 Answers2

2

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.

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