-2

In this case when n is a number parameter in the function. Why is toString(2) going to n % 2 and return the divisor remainder? I thought that toString just return a number into a string.

+n.toString(2) 

function toBinary(n) {

  var toBinary2 = +n.toString(2)

  return toBinary2

}
console.log(toBinary(2))
JLRishe
  • 99,490
  • 19
  • 131
  • 169
EdgarChe
  • 11
  • 2
  • 5

2 Answers2

0

The parameter to Number#toString is a base.

Calling .toString(2) on a number will return that number in binary.

2 in binary is 10, so that is why (2).toString(2) returns 10.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • haa ok, so If I put a parameter into toString(2) is going to return the binary number. Thank you so much! – EdgarChe Jan 12 '18 at 13:06
0

Why is toString(2) going to n % 2 and return the divisor remainder?

toString takes radix as parameter and toString(2) converts the number into binary equivalent string.

+Number(2).toString(2) converts the binary equivalent to the number again, but doesn't do binary to decimal conversion.

So, +Number(2).toString(2) => +"10" => 10

gurvinder372
  • 66,980
  • 10
  • 72
  • 94