-1

this code is supposed to display a random character/ letter of a given name in javascript using while loops and if statements . . . the problem that I faced is that the RandomLetterIndex is between 0 and 5 (<=5) when I want it to be between 0 and 4 (<5)

const MyName = "Ayman";
var RandomLetterIndex = Math.floor(Math.random() * 10);

while (RandomLetterIndex > MyName.length) {
  RandomLetterIndex = Math.floor(Math.random() * 10);
  if (RandomLetterIndex < MyName.length && RandomLetterIndex !== 5) {
    break
  }
}

console.log(RandomLetterIndex);
console.log(MyName.charAt(RandomLetterIndex));
Andy
  • 61,948
  • 13
  • 68
  • 95
  • You don't need that while loop. Just adjust your randomiser: `const RandomLetterIndex = Math.floor(Math.random() * (MyName.length - 0) + 0);` and simply log the result. – Andy Sep 08 '21 at 10:00

3 Answers3

3

If you want the random number to be less than the length of the word, instead of using while loops, you can do this

var RandomLetterIndex = Math.floor(Math.random()*MyName.length);

multiplying by length instead of 10 makes sure that the value always lies in the range [0, length-1] instead of [0, 10-1]

Muhammed Jaseem
  • 782
  • 6
  • 18
1

The problem is with the 0 based index and the length property. MyName.length will equate to 5 and thus the while loop will stop and the consoles print out.

while (RandomLetterIndex > MyName.length - 1) {

Try like this with the minus 1.

spirift
  • 2,994
  • 1
  • 13
  • 18
0

Your while loop ends when RandomLetterIndex is 5. Thats why you see a five in the console.

Also, you are breaking the loop, and therefore the while check is kind of useless.

Mario
  • 8,253
  • 2
  • 14
  • 29