javascriptundefinedvariable-initialization

Variable initialization in Javascript


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}`);

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?


Solution

  • 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.