Am new to JavaScript, I have this code where am trying to generate a random background color, which actually worked but the color title is not in alignment
const color = ["red", "green", "yellow", "blue"];
let header = document.getElementById("header");
let container = document.getElementById("container");
function flip() {
container.style.backgroundColor = color[getRandomColor()];
header.textContent = color[getRandomColor()];
}
function getRandomColor() {
for (let i = 0; i < color.length; i++) {
return Math.floor(Math.random() * color.length);
}
}
I have tried it without the for loop
and nothing worked again
4
Answers
That’s the thing about generating a random number… It’s random. So it might not be the same number twice in a row.
Every time you call
getRandomColor()
it returns a random number. (Not a random color, as its name suggests.) And you call it twice:Given the length of your array, there’s only a 25% chance that these two function calls will result in the same index being chosen in that array.
If you just want one random number, call the function once and use the resulting value twice:
As an aside…
Your
for
loop isn’t doing anything meaningful, as you’ve guaranteed that it will only ever iterate once by returning from that iteration. You may as well remove it:first save the value of getRandomColor() into a variable then you can use the same value on both.
Define a variable and store the random index in that variable