Facing difficulty in understanding Recursion

const decimalToBinary = (input) => {
 if (input === 0) {
  return "0";
 } else {
  return decimalToBinary(Math.floor(input / 2)) + (input % 2);
 }
};

Please help me understand this, I am unable to think how else block code in working. I even tried on notebook but it doesn’t helps.

is that (input% 2) a string data type ? If yes then how ?

(input % 2) will not be a string, regardless if input is a string or not. You can try that in the browser’s console:

> '11' % 2
1
> 11 % 2
1
> '10' % 2
0
> 10 % 2
0
1 Like

if you are asking how the output becomes a string, it starts with the return "0"

so after that, you have return "0" + (input % 2)

1 Like

Block code explanationon:

  • Math.floor(input / 2): moves one step closer to the base case
  • decimalToBinary(...): recursive call processes the “rest” of the number
  • input % 2: gives you the current digit (remainder)
  • + joins the binary string in correct order

To convert a decimal number to binary:

  • Divide the number by 2
  • Write down the remainder (0 or 1)
  • Repeat the process with the quotient (whole part of division)
  • Stop when the number is 0
  • Read the remainders in reverse

For example:
13 ÷ 2 = 6 remainder 1
6 ÷ 2 = 3 remainder 0
3 ÷ 2 = 1 remainder 1
1 ÷ 2 = 0 remainder 1
→ Binary = 1101

I made this codepen for easy visualizing https://codepen.io/chandrika11p11/pen/XJbbgzy

1 Like

but If I Input a no. greater than 0 like 5 for e.g. then if block will not run then how it will convert to string ?

yes you’re right, I forgot that. Thank you.

That JS is difficult to understand for me, I am not familiar with few things but that text explanation helped. Thank you.

eventually it will be 0, because of this. Any number divided by 2 enough times it will become 0

yes, so that converts to string at the end due to type coercion ?

yes, because using + with a string and a number gives back a string, so it’s always "0" + some number

1 Like