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

152
Vistas
How to find square of n with a for loop javascript

Can someone walk me through the following code:

function square(n) {
    let result = 0;
    for (let i = 1; i <= n; i++) {
        for (let j = 1; j <= n; j++) {
            result += 1;
        }
    }
    return result;
}

//
example: 

console.log(square(5)) // 25

How does this for loop work in creating a square of an n number? I don't know where to start in approaching how this works.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The square of a number can be visualized as the number of squares in a grid. 5x5, for example, is 5 wide by 5 tall:

enter image description here

You can think of the nested loop in your code

for (let i = 1; i <= n; i++) {
    for (let j = 1; j <= n; j++) {
        result += 1;
    }
}

emulating movement along the grid.

When i is 1, it's going along the first row. When j is 1, that corresponds to the first column. That corresponds to the first square. Next iteration corresponds to the first row, second column - etc, until i <= n is no longer fulfilled, at the end of the row. The next row then iterates n times, and so on.

You'll see that the number of total iterations (where result += 1 runs) is equivalent to n * n, as the nested loop implements.

about 4 years ago · Juan Pablo Isaza Denunciar

0

In short, the inner(j) loop runs 5 times for every iteration of the outer(i) loop..

Basically,

for each i = 1, j runs 5 times
for i = 2, j runs 5 times //total 10 times
for i = 3, j runs 5 times //total 15 times
for i = 4, j runs 5 times //total 20 times
for i = 5, j runs 5 times //total 25 times

So the result gets incremented 25 times, and hence the answer is 25

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