What does parameter in Array toString do?

Viewed 126

I saw a code like this. I looked up MDN but there's no mention about toString having parameters. What does 3 do inside n.toString(3)?

function solution(n) {
  n = n.toString(3).split('').reverse().join('')
  return parseInt(n, 3)
}



3 Answers

This is Number.prototype.toString(), not Array.prototype.toString(). It takes radix as an optional parameter.

An integer in the range 2 through 36 specifying the base to use for representing numeric values.

Your code converts n to base-3. If you want to convert a number to binary, you'd do n.toString(2)

const n = 16,
      bases = [2, 3, 4, 10, 16]

console.log(
  bases.map(radix => n.toString(radix))
)

It is an optional parameter when converting number to string:

Optional. Which base to use for representing a numeric value. Must be an integer between 2 and 36. 2 - The number will show as a binary value 8 - The number will show as an octal value 16 - The number will show as an hexadecimal value

This is the Radix (a number represent base-3 numeral system or any other numeral systems). For example if you put 2 instead of 3 this function convert the result into the binary system. you can put from 2 - 36 in it as the parameter.And the default value is 10 and this parameter is completely optional.

test this one:

var x = 10;
x.toString(2); // output: "1010"
Related