Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!