-3

Could anyone explain why the result is 5?

console.log(parseInt('101', 2)); // 5
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Ahmad
  • 1
  • Because the second param is a radix, and the number 2 makes the parse interpret as binary number. More about that you can find here https://stackoverflow.com/questions/6611824/why-do-we-need-to-use-radix-parameter-when-calling-parseint https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt – Ion Dec 11 '20 at 16:31

2 Answers2

4

The second argument to parseInt specifies the number base.

Base 2 is binary.

101 in binary is (1*4 + 0*2 + 1*1 =) 5 in decimal.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

The second argument you are passing to parseInt function is called Radix.

When you are passing 2 means that the string is in binary so the binary of 5 is 101.

5 (Decimal) = 101 (Binary)

That is why you are getting 5 as int.

dev_mustafa
  • 1,042
  • 1
  • 4
  • 14