Why it's not possible by doing it like this?

Why it’s not possible by doing it like this?

 function convertToInteger(str, radix) {

return parseInt(str, radix);
}
console.log(convertToInteger(“10011”, 2));


function convertToInteger(str, radix) {
return parseInt(str, radix);
}
console.log(convertToInteger("10011", 2));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36 Edg/88.0.705.81.

Challenge: Use the parseInt Function with a Radix

Link to the challenge:

You changed the given function stub, which means tha the function you wrote will not work with the test suite.

function convertToInteger(str) {
1 Like

The tests are calling the function for you, it does not expect nor pass anything to the radix parameter, so it will be undefined.

assert(convertToInteger('10011') === 19);

If you assign a default value to the parameter it will work.

function convertToInteger(str, radix = 2) {
  return parseInt(str, radix)
}

However, keep in mind that it’s generally not a good idea to change the function signature as you do not control how the function is being called by the tests and you do not know what is checked for (for example, there might be a regex check).

1 Like

I think the guys above explained what was going on pretty well so not much more to say about that, but one thing I would like to discuss is arguments, and when to use them. Generally speaking we use arguments so a function can take different, but similar input, e.g., a function that adds can either be very useful if its written like this function add (a, b) { return a + b; }, or it could be only used for one thing if we wrote it like this function add () { return 1 + 1; } so you can see a how a small difference adds a large amount of functionality, but on the same toke what if I want to add a number that is n to the number 2? Well I can write the add function as such function add (n) { return 2 + n; } as you can see I only provided one argument as I know the other number will always be 2, and the same is true for your convertToInteger function, you always know you will be handed a string of binary numbers so there is no point in the function requesting for a radix argument as you know the radix will always be 2 so you can just hand that directly to parseInt.

1 Like

Thank u! It was really enlightening!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.