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?
3
Answers
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
Try to find the values in
arr_1
andarr_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.The answer is because you are adding
r1 += arr_1[i];
which meansundefined+=arr_1[i]
for the first time. since undefined cannot be added with, it returnsNaN
for each and every addition done from first to last. But intotal
case, you are assigning the valuetotal=r1+r2
so in that case even if total wasundefined
it was reassigned another value, which wasr1 + r2
. So in short, you cannot add to anundefined
value but you can assign another variable to anundefined
value. Hope it answers the question.