1

I'm very new to code so I might not understand some answers. I'm having trouble turning a variable into a random number between 1 and 10 in this code.

<script type="text/javascript">
var money = 0

function Random() {
  money = Math.floor((Math.random() * 10) + 1);
}
</script>

I've read that I need to put return followed by the randomizing code somewhere but I just don't understand where I place that on how I use it.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
  • 1
    You probably meant to replace `money =` with `return`. Then you can call `money = Random()` to change `money` to a new random integer between 1 and 10. – Patrick Roberts Feb 28 '18 at 09:44
  • 1
    Why are you using a function at all? – melpomene Feb 28 '18 at 09:44
  • Possible duplicate of [Generate random number between two numbers in JavaScript](https://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript) – KolaCaine Feb 28 '18 at 09:54

2 Answers2

2

function Random() {
  return Math.floor((Math.random() * 10) + 1);
}

function getRandom() {
  var money = Random();
  console.log(money);
  document.getElementById("demo").innerHTML = money;
}
<button onclick="getRandom()">Click for random number</button>

<p id="demo"></p>
fyasir
  • 2,924
  • 2
  • 23
  • 36
  • `var money = Math.floor((Math.random() * 10) + 1);` – melpomene Feb 28 '18 at 09:48
  • @melpomene Your approach is also right. I duplicate the question and fixed the issue. – fyasir Feb 28 '18 at 09:50
  • This worked well for the most part but I couldn't work out how to link this to a button. I tried changing a buttons signal to Random but it didn't work. Do you know how I could make a button set off this function so that when i click the button it randomizes the value of the variable? – riley sampson Mar 02 '18 at 09:32
0

This line will work:

var money = Math.floor((Math.random() * 10) + 1);

But if you want to use a function, you can write it:

var money;

function Random() {
  return Math.floor((Math.random() * 10) + 1);
}

// Re-usable anytime you want
money = Random();
Magus
  • 14,796
  • 3
  • 36
  • 51