+7

# The following outputs 11, 704 and 124 but I can't wrap my head around the reason for their output. Please help a brother..

function addBinary(a,b) { var sum=a+b; var res=””; while(sum>0) { res=sum%2+res; sum=Math.floor(sum/ 2); } } alert(addBinary(1,2)); //11 var input=407; var res=0; for(i=input;i>0;i=Math.floor(i/10)) { res=res*10+i%10; } document.write(res); //704 var arr=; for(var i=1; i<3; i++) { arr[i] = arr[i-1]+i; } alert(arr.join(“”)); //124

+9

I'm trying to explain third program. var arr = ; // arr = 1; The loop start with i = 1 and arr[i] = arr[i-1] + 1 is arr = arr[1-1] + 1 = 1+1=2 Next step i = 2. arr[i] = arr[i-1] + 1 is arr = arr[2-1] + 1 = 2+2=4.

+8

Look inside the loop you have arr [i] = arr [i-1] + i. So arr [i-1] is 1 and plus i.

+3

You probably wanted to write i > 0, since that actually makes sense i in the loop starts as 407. res is 0, so res * 10 + i % 10 is 7. Then, at the end of the iteration, i becomes Math.floor(i / 10), which is 40. res * 10 + i % 10 is 70, since 7 * 10 (70) + 40 % 10 (0) is 70. Then, again, i becomes i / 10 (4). res * 10 + i % 10 = 70 * 10 (700) + i % 10 (4) = 704. 4 divided by 10 is 0(.4), so the loop stops executing. (it gets reversed)

+3

arr = 1 arr = arr + 1 -> 2 arr = arr + 2 -> 4

+3