Search code examples
javascriptstringloopsintparseint

Having issues converting string to int using parseInt() function


function largestNumber(n) {
  let output = "";
  var toInt = parseInt(output);
  for (let i = 1; i <= n; i++){
    output = output + "9";
  }
  return output;
};

I dont know exactly how to get this to return an integer. I keep getting null, or no output. I have tried

 return output.toInt;

 var toInt = output.parseInt();
 var toInt = output.parseInt(output);
 var toInt = output.parseInt("output");
 var toInt = parseInt(output);
 var toInt = parseInt(output,10);

and a few other various ideas that I dont remember by this point xD. the help is greatly appreciated!

EDIT

Thanks for the help guys I found the problem in my code was the

var toInt = parseInt(output); 

needed to come after the loop and then call

return toInt;

However, Barmar (I hope I spelled your name right) has a much cleaner effective solution.


Solution

  • Your current code always attempts to parse an integer from output, but you always initialize output to an empty string right before the parse, so you get no int as a result.

    You need to wait until output has been built up to its final value before you use parseInt().

    function largestNumber(n) {
      let output = "";
      for (let i = 1; i <= n; i++){
        output = output + "9";
      }
      return parseInt(output);
    }
    
    console.log(largestNumber(5));
    console.log(largestNumber(15));

    But really, this can be done in a much simpler way based on what your logic is currently doing:

    function largestNumber(n) {
      return parseInt("9".repeat(n));
    }
    
    console.log(largestNumber(5));
    console.log(largestNumber(15));