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
, andtotal
). - However, after I initialized the
r1
andr2
. 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?