-2

I'm having difficulty creating a random string of words to be used in a typing speed test.

The String generator file I wrote is as follows:

const WordGenerator = () => {
  const WordBank = [
    'difficulty',
    'never',
    'furniture',
    'thus',
    'transportation',
    'opportunity',
    'beautiful',
    'exactly',
    'standard',
    'kept',
    'baseball',
    'perfectly',
    'term',
    'egg',
    'must',
    'fix',
  ];
  let result = '';
  
  for (let i; i <= 200; i++) {
    result = result.concat(WordBank[Math.floor(Math.random() * 16)], ' ');
  }
  
  return result;
};

console.log(WordGenerator());

For some reason when I console.log this, it returns an empty string. I was hoping to have a string of 200 random words from the word bank.

Any suggestions?

ps: I had to remove words from the word bank because stack overflow wasn't allowing me to have so much code, Im originally using 250 words in the wordBank.

biberman
  • 5,606
  • 4
  • 11
  • 35

1 Answers1

2

Your issues are: 1- in the for loop you didn't initialize the variable i to start from 0:

 for (let i ▶️= 0 ◀️; i <= 200; i++) 

2- when getting a random index why are you using (250), you need to use the array length:

const WordGenerator = () => {
  const WordBank = [
    'difficulty',
    'never',
    'furniture',
    'thus',
    'transportation',
    'opportunity',
    'beautiful',
    'exactly',
    'standard',
    'kept',
    'baseball',
    'perfectly',
    'term',
    'egg',
    'must',
    'fix'
  ]

  let result = ''
  for (let i = 0; i <= 200; i++) {
    result = result.concat(WordBank[Math.floor(Math.random() *  WordBank.length)] +' ')
  }
  return result
}

console.log(WordGenerator());
Liam
  • 27,717
  • 28
  • 128
  • 190
Abd Elbeltaji
  • 473
  • 2
  • 13