Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

148
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda