Adding Two Numbers doesn't give the calculated result instead it concatenates them

This is the Question:
Get the sum of two arrays…actually the sum of all their elements.
P.S. Each array includes only integer numbers. Output is a number too.

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
// Example output: 
// 276 + 351 = 627

MyCode:
    function Sum(arr){
      sum=0;
      for(let i=0;i<arr.length;i++){
        sum+=arr[i];
      }
      return sum;
    }
    let sum=0;
    let arr_1 = [3, 5, 22, 5,  7,  2,  45, 75, 89, 21, 2];
    let arr_2 = [9, 2, 42, 55, 71, 22, 4,  5,  90, 25, 26];
    console.log("Sum_1: "+Sum(arr_1));  //This one returns Sum_1: 276
    console.log("Sum_2: "+Sum(arr_2)); //This one returns Sum_2: 351
    console.log("Final_Sum: "+Sum(arr_1)+Sum(arr_2));

Doubt:
console.log("Sum_1: "+Sum(arr_1));  //This one returns Sum_1: 276
console.log("Sum_2: "+Sum(arr_2)); //This one returns Sum_2: 351
The above two returns its calculated result but the console.log("Final_Sum: "+Sum(arr_1)+Sum(arr_2)); returns me 276351. It concatenates them instead of adding them. I did typeOf(Sum(arr_1)) and typeOf(Sum(arr_2)). Both gives me the result as number.Then why is it concatenating them. Could someone clear my doubt.
Thanks in advance!!!

Whenever you concatenate anything with a String, the output will be a String. Even if
you did
let result = 432 + "";
result would equal "432"

In your case, I would write the sum in backticks, which carries out the sum before concatenating:
console.log("Final_Sum: " + `${ Sum(arr_1) +Sum(arr_2) }` );

You could also just assign the sum to a variable and concatenate that variable with "Final_Sum: "

Hello @Deepi_code

plus what @Liam_Idrovo said

you can also use the () which override the precedence

 console.log("Final_Sum: "+(Sum(arr_1)+Sum(arr_2)));

notice i used the power of order to make the addition happen first

  • will do the addition as long as the to side or the + are numbers but if one of both side are string it will be concatenation

and have a nice day for both of you :slight_smile: