1

I'm a total newb here learning how to code :) Hoping someone can shed some light on the following.

I'm writing some code in JavaScript to generate a random mix of 6 letters from the alphabet using a Math.random method and a for-loop.

I can get this to work when I write the code 'Math.floor(Math.random() * alphabet.length)' directly into the array index however when I assign it to a variable and use that as the index instead, I end up with a 'random' letter that's duplicated 6 times.

Is it possible to assign a random value (using the Math.random method) to a variable and have it execute each time it goes through the loop? Thanks in advance!

This is the code that works:

var alphabet = "abcdefghijklmnopqrstuvwxyz";
var randomString = "";

for (var i = 0; i < 6; i++) {
randomString += alphabet[Math.floor(Math.random() * alphabet.length)];

console.log(randomString);
}

Output code example: xuhmwg

This code ends up with duplicated letters:

var alphabet = "abcdefghijklmnopqrstuvwxyz";
var randomString = "";
var randomNumber = Math.floor(Math.random() * alphabet.length);

for (var i = 0; i < 6; i++) {
randomString += alphabet[randomNumber];

console.log(randomString);
}

Output code example: dddddd

Codlll
  • 11
  • 3
  • 2
    put this `var randomNumber = Math.floor(Math.random() * alphabet.length);` inside the loop before `randomString += alphabet[randomNumber];` – Kenny May 05 '22 at 11:28
  • 3
    Run the code with a debugger to see what's happening. Simply put, assigning a value to a variable assigns it once. Change it to `var randomNumber = () => Math.floor(Math.random() * alphabet.length);` and use `randomString += alphabet[randomNumber()];` – Heretic Monkey May 05 '22 at 11:28
  • Does this answer your question? [Generate random string/characters in JavaScript](https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript) – Heretic Monkey May 05 '22 at 11:32
  • Thanks all, Kenny's suggestion of adding it in the loop before randomString worked a charm! – Codlll May 05 '22 at 12:35

1 Answers1

-1

This is how I would do it.

var alphabet = "abcdefghijklmnopqrstuvwxyz";
var randomString = "";

for (var i = 0; i < 6; i++) {
randomString += alphabet[Math.floor(Math.random() * alphabet.length)];
console.log(randomString);
}
olifire
  • 47
  • 6