1function add(str1, str2) {
2
3 let sum = ""; // our result will be stored in a string.
4
5 // we'll need these in the program many times.
6 let str1Length = str1.length;
7 let str2Length = str2.length;
8
9 // if s2 is longer than s1, swap them.
10 if(str2Length > str1Length ){
11 let temp = str2;
12 str2 = str1;
13 str1 = temp;
14 }
15
16 let carry = 0; // number that is carried to next decimal place, initially zero.
17 let a;
18 let b;
19 let temp;
20 let digitSum;
21 for (let i = 0; i < str1.length; i++) {
22 a = parseInt(str1.charAt(str1.length - 1 - i)); // get ith digit of str1 from right, we store it in a
23 b = parseInt(str2.charAt(str2.length - 1 - i)); // get ith digit of str2 from right, we store it in b
24 b = (b) ? b : 0; // make sure b is a number, (this is useful in case, str2 is shorter than str1
25 temp = (carry + a + b).toString(); // add a and b along with carry, store it in a temp string.
26 digitSum = temp.charAt(temp.length - 1); //
27 carry = parseInt(temp.substr(0, temp.length - 1)); // split the string into carry and digitSum ( least significant digit of abSum.
28 carry = (carry) ? carry : 0; // if carry is not number, make it zero.
29
30 sum = (i === str1.length - 1) ? temp + sum : digitSum + sum; // append digitSum to 'sum'. If we reach leftmost digit, append abSum which includes carry too.
31
32 }
33
34 return sum; // return sum
35
36}