2

Trying to create a random letter generator with a "while" loop. It's return one value into the randomString and then quits the loop.

var alpha = "abcdefghijklmnopqrstuvwxyz";

var randomString = "";

while (randomString.length < 6) {
  console.log(randomString += alpha.charAt(Math.floor(Math.random() * alpha.length)));

  randomString++;
}

Returns one value from alpha string to randomString and then quits the loop instead of going on for 4 more loops - condition set at (randomString.length < 6).

3
  • 7
    Idk what randomString++ is going to do on a string - but that might be an issue. (It returns NaN) Commented Nov 3, 2016 at 19:30
  • why do you use the randomString++ function? This sets for adding a number on top of it's older value. you can delete this line Commented Nov 3, 2016 at 19:31
  • 1
    In other words, just get rid of randomString++; Commented Nov 3, 2016 at 19:31

2 Answers 2

2

Incrementing a string results in NaN, which doesn't have a length property, so the loop ends after one iteration.

Don't increment your randomString:

  var alpha = "abcdefghijklmnopqrstuvwxyz";

  var randomString = "";

  while (randomString.length < 6) {
    console.log(randomString += alpha.charAt(Math.floor(Math.random() * alpha.length)));
  }

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

Comments

0

create a variable and set is an empty string. Then, create a while loop that will continually add new random letters to this string, as long as the string length is less than 6 or any length you choose. += operator to add a new letter to the end of the string.

var alphabet = "abcdefghijklmnopqrstuvwxyz";
var randomString = "" // first, create an empty string

while (randomString.length < 6) {
    console.log(randomString += alphabet[Math.floor(Math.random() * alphabet.length)]);
    randomString++;
}

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.