0

I have the following javascript code:

  let gemStones = [
  "Amethyst",
  "Diamond",
  "Emerald",
  "Ruby",
  "Sapphire",
  "Topaz",
  "Onyx",
];

let randomGemStone = gemStones[Math.floor(Math.random()*gemStones.length)];

function findGems()
{
  console.log("You found a " + randomGemStone + "!");
}

Here's the html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="css.css">
  <title>1. Gem Pond</title>
</head>
<body>
  <h1>Gem Pond</h1>
  <script src="main.js"></script>
  <button id="gemPond_btn" onclick="findGems()">GET GEM</button>
</body>
</html>

When I click the "GET GEM" button several times in a row, I always get the same result instead of getting a random one.

I'm not sure what I'm doing wrong here.

Thanks in advance.

1
  • What about turning randomGemStone into a function? randomGemStone = () =>? then call that in findGems? console.log("You found a " + randomGemStone() + "!"); Commented Apr 19, 2021 at 20:16

2 Answers 2

3

Move the let randomGemStone line into the findGems function:


function findGems()
{
  let randomGemStone = gemStones[Math.floor(Math.random()*gemStones.length)];
  console.log("You found a " + randomGemStone + "!");
}

Otherwise you run it only once on page load and not every time you click the button.

Sign up to request clarification or add additional context in comments.

2 Comments

If randomGemStone value will not change you can use const instead of let
Thank you. It made perfect sense once I read your comment.
1
 let gemStones = [
  "Amethyst",
  "Diamond",
  "Emerald",
  "Ruby",
  "Sapphire",
  "Topaz",
  "Onyx",
];


const findGems = () => {
  let randomGemStone = gemStones[Math.floor(Math.random()*gemStones.length)];
  console.log(`You found a ${randomGemStone}!`);
}

Note I have moved randomGemStone inside the function. Or the value will only be updated once when the script loads, this way it will be random everytime findGems() is called

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.