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

147
Visualizações
Why does the modulo operator appear to work differently in FOR loops in javscript?

I'm making a simple javascript function that takes an input of a string and pads it to the nearest multiple of 8. The function works, however it appears that the modulo operator works differently in for loops. For example:

var text = "abcdefghi"
if(text.length % 8 !== 0){
  var amt = 8 - (text.length % 8)
  for (let i = 0; i < amt; i++) {
    text = text + "#"
  } 
}
console.log(text)

Returns: abcdefghi#######

But:

var text = "abcdefghi"
if(text.length % 8 !== 0){
  for (let i = 0; i < text.length % 8; i++) {
    text = text + "#"
  }
}
console.log(text)

Also Returns: abcdefghi#######

From my understanding of the modulo operator text.length % 8 = 1 given a string input of 9 characters. So therefore in order to pad the string to make it 16 characters I would have to do 8 - (text.length % 8) = 7. When I put that into it's own variable so that amt = 7 the for loop loops 7 times and works correctly. However, when I do the operation in the for loop and remove 8 - it also loops 7 times even though text.length % 8 = 1. Can someone explain what's going on here?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The for loop will evaluate the length of the text every time it runs through the loop. So if you add a hashtag onto the end of the text in the loop, when it evaluates the length again, it will see that the text is one longer than it was last time.

So basically you are adding the text than finding the length again, when you get the length of text outside the for loop, you will get a constant of the length and be able to accurately use it in the for loop.

To put it to an example, when you do the constant length, like what you did in your first example outside of the for loop, you have an equation like:

repeat until x = y

But if you do the calculation inside the for loop, you get an equation like:

repeat until x = x + 1

That just doesn't work because x is not going to equal itself + 1 if you recalculate what x + 1 is every time you increment x.

about 4 years ago · Juan Pablo Isaza 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