Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

80
Visualizações
Need to understand how for loop is working in the The Color Flipper code below
Code : 

const hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];
const btn = document.getElementById("btn");
const color = document.querySelector(".color");

btn.addEventListener("click", function () {
  let hexColor = "#";
  for (let i = 0; i < 6; i++) {
    hexColor += hex[getRandomNumber()];
    console.log(hexColor);
    color.textContent = hexColor;
    document.body.style.backgroundColor = hexColor;
  }
});

function getRandomNumber() {
  return Math.floor(Math.random() * hex.length);
}

Here i am unable to understand how for loop is running. How for loop is establishing connection with getRandomNumber() function. Could someone please explain how for loop is operating in regards to this code step by step please?

Thank You

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

getRandomNumberFunction returns a random value from the hex variable as you can see here

function getRandomNumber() {
  return Math.floor(Math.random() * hex.length); // this returns a random number based on the length of the hex which is 16 it will choose from 0-15
}

then append the value taken to the variable hexColor which is initially assigned with "#"

   hexColor += hex[getRandomNumber()]; // initial value "#" + "hex[0-15] random digit"

At the end of the code it will look something like this hex code #32a856 because it will only run for 6 turns then that will be set to the background color of body element

about 4 years ago · Santiago Trujillo Relatório

0

What happens in getRandomNumber() is whenever the function is called, it generates a random number between 0-15 (which is the length of the array hex[])

More information about JavaScript Math here


For how it is used inside the for loop:
for (let i = 0; i < 6; i++)
  1. let i = 0 We initially defined the variable i with 0 as its value.

  2. i < 6 This is the condition of the loop. This means when this condition is true, the code inside the loop will re-run until it becomes false.

  3. i++ This is like the 'do' part of the loop. So whenever the condition is met, this is the action that will be done to the variable we initially defined. In this case, the value i gets incremented (++)/i=i+1.

  4. When the loop happens, hexColor gets concatenated with a random value from the array hex[]

    hexColor += hex[getRandomNumber()];
    

For instance:

If function getRandomNumber() output is = 11. Then, hex[getRandomNumber()] output is = hex[11]. In which hex[11] = "B". Therefore hexColor becomes #B - This gets repeated six (6) times until the 6 characters are completed. Sample output
Loop 1: #B
Loop 2: #B3 ... so on


However in the code you provided, the lines:
color.textContent = hexColor;
document.body.style.backgroundColor = hexColor;

is inside the for loop. Which means color.textContent and document.body.style.backgroundColor is being set 6 times. Which should be not and it should just be set whenever the loop is completed.

Here is a code sample where I moved the said lines outside the loop so it would just change color.textContent and document.body.style.backgroundColor once the hexColor/loop is completed.

const hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];
        const btn = document.getElementById("btn");
        
        btn.addEventListener("click", function () {
          let hexColor = "#";
          for (let i = 0; i < 6; i++) {
            hexColor += hex[getRandomNumber()];
          }
          document.getElementById('color').innerHTML = hexColor;
          document.body.style.backgroundColor = hexColor;
        });
        
        function getRandomNumber() {
          return Math.floor(Math.random() * hex.length);
        }
<html>
  <body>
    <p style="font-size:48px">Color (hexColor) value: <span id="color"></span> </p>
    <button id="btn" style="padding: 20px;">Get Random Color</button> 
  </body>
</html>

Hope this helps!

about 4 years ago · Santiago Trujillo Relatório

0

There are many details answers here, however, since your question is about the for loop.

The following means it will call the getRandomNumber() 6 times, so it will place random chars from your hex array, forming a 6 char long string (e.g. #847ABC)

let stringToBeCreated = '';
for (let i = 0; i < 6; i++) {
   console.log('value of i', i);
   stringToBeCreated += i; // this is replaced by your randomNumber and hex array
}

console.log('string created', stringToBeCreated)

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda