'Random text in javaScript

I'am trying to make a random function that every time that apper, apper with a different text

I have done a array like this:

let text = ['Oh Noo!!', 'You lost!', 'Try a next time!!'];

and here is the function:

function drawGameEnd() {
  
  if (gameOver || gameWin) {
      text = "Congrats!🥳";
    if (gameOver) {
      text = text[Math.floor(Math.random() * text.length)];
    }

    ctx.fillStyle = "#2215d6";
    ctx.fillRect(0, canvas.height / 4, canvas.width, 190); //canvas text gradientes

    ctx.font = "28px Comic Neue";
    const gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
    gradient.addColorStop("0", "#fff");

    ctx.fillStyle = gradient;
    ctx.fillText(text, 20, canvas.height / 2.2);

  }
}

But when a run it, it only show one letter of the word... How can i fix it?



Solution 1:[1]

That's because you defined text as a string

const texts = ['Oh Noo!!', 'You lost!', 'Try a next time!!'];;
text = texts[Math.floor(Math.random() * texts.length)];
console.log(text)

Solution 2:[2]

It's because you are reassigning the variable text which holds your array of text options, to hold the single word you chose. The next time drawGameEnd is called, rather than selecting a single word in the original array, it selects a single letter from that word.

Only reason this bug didn't result in an error is because a string is kinda like an array of characters, so syntactically it checks out for the first two times drawGameEnd is called... untyped JS is wild.

Solution 3:[3]

You've defined a variable called text and set it to an array of strings:

let text = ['Oh Noo!!', 'You lost!', 'Try a next time!!'];

Then what do you do with text?...

text = "Congrats!?";

or:

text = text[Math.floor(Math.random() * text.length)];

Now it's not an array. Now it's a string. The array is gone. (And, later, if you treat a string as an array then it's an array of characters.)

The lesson here is that you shouldn't try to store everything in the same variable. Because once you do, you overwrite whatever was previously stored in that variable.

Use different variable names. And convey information about what the variable is in those names. For example:

let textOptions = ['Oh Noo!!', 'You lost!', 'Try a next time!!'];
let text = '';

and:

if (gameOver || gameWin) {
  text = "Congrats!?";
  if (gameOver) {
    text = textOptions[Math.floor(Math.random() * textOptions.length)];
  }
  //...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bob
Solution 2 user6118986
Solution 3 David