Search code examples
javascriptperformancemathrandomparseint

Better way to use parseInt() to change users' promt() into numbers


I set up a function to ask users a range of numbers, and gave them back a random number. The first try is okay.

// function settings
function getRandom(lower, upper) {
  return Math.floor(Math.random()*(upper-lower+1))+lower;
}

// ask users to give a range of numbers
var lowerNum = parseInt(prompt("lower number?"));
var upperNum = parseInt(prompt("upper number?"));

document.write(getRandom(lowerNum, upperNum));


However, I thought it would be better to take parseInt() inside the function, so that it would be more clear and semantic.

// function settings
function getRandom(lower, upper) {
  lower = parseInt(lower);
  upper = parseInt(upper);
  return Math.floor(Math.random()*(upper-lower+1))+lower;
}

// ask users to give a range of numbers
var lowerNum = prompt("lower number?");
var upperNum = prompt("upper number?");

document.write(getRandom(lowerNum, upperNum));

Both blocks of codes can do well and get the same results. But which one is the better practice, or even performance when running the program?


Solution

  • Use whatever is more readable for you, yet if you're trying to squeeze that extra bit of performance, try cleaning elsewhere, like dropping those two temporary variables, using bitwise-flooring, etc... (looks ugly, yes):

    function getRandom(lower, upper) {
      return (Math.random()*(upper-lower+1) | 0) + lower;
    }
    
    alert(getRandom(parseInt(prompt("lower number?"), 10), parseInt(prompt("upper number?"), 10)));


    Performance tests

    You'll see your two cases are usually close to each other, my approach is slightly faster, and you go turbo when you don't parse integers.