Fix The Broken Code! Explanation of the Inner Loop

Hey everyone,

So I am having some trouble understanding how this inner loop is working.

const numbers = [5, 3, 9, 30];

const smallestPowerOfTwo = arr => {

      let results = [];

      // The 'outer' for loop - loops through each element in the array

      for (let i = 0; i < arr.length; i++) {

            number = arr[i];

            // The 'inner' while loop - searches for smallest power of 2 greater than the given number

            j = 1;

            while (j < number) {

                  j = j * 2;

            }

            results.push(j);

      }

      

      return results

}

I understand what the question is asking for and got the answer correct. I just can’t figure out how the nested loop is working.

Could someone help me understand how the inner j loop is looping through numbers without having like a j++ and how it’s checking if it’s the lowest power?

Thanks a bunch!

we can visualize the execution of the inner loop/break it down into steps

lets do this for the first element of the numbers array, so then we have number = 5

so first we have j = 1, which means the loop condition becomes:

while (1 < 5)

this is true, so we get:

j = 1 * 2

so now j = 2, so again the loop condition is evaluated:

while (2 < 5)

this is still true, so now we get:

j = 2 * 2

so j = 4.
which means we get:

while ( 4 < 5) // true
j = 4 * 2 // j = 8
while ( 8 < 5) // false

the loop has become false, so now we have 8, which is pushed to the array

A for loop with an increment (like i++) is useful if we know the amount of times the loops need to run (amount of elements in the array) and a while loop is useful when we don’t know the amount of iterations

2 Likes

Thank you so much! This totally makes sense now! :slight_smile:

Thank you so much! :bowing_woman:t4: