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

155
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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