Fix The Broken Code!

Hi All,

I can’t for the life of my figure this challenge out. Here is the link: https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/web-dev-intermediate-javascript-practice/lessons/intermediate-javascript-coding-challenge/exercises/fix-the-broken-code

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

const smallestPowerOfTwo = arr => {
      let results = [];
      // The 'outer' for loop:
      for (let i = 0; i < arr.length; i++) {
            number = arr[i];
        

            // The 'inner' while loop:
            // We needed to create a new variable!
            let j = 1;
            while (j < number) {
                  j = j * 2;
              
            }
            results.push(j);
      }
      return results
}

console.log(smallestPowerOfTwo(numbers)) 

The output is [ 8, 4, 16, 32 ]

But I can’t figure out how to get the first value “8” in the array.

If j = 1

while( 1 < number)
j = 1 * 2

J is equal to 2 now.

Thanks

Your code seems fine. Are you asking why/how the first number in the results array is an ‘8’?

Hi @ktsotras thanks for responding. Yes, I got the solution from Codecademy but I do not understand how we get to it. I think I understand how it got to elements 4, 16, 32 but I cannot figure out the first element.

It is because ‘8’ is the lowest power of 2 that is still greater than ‘5’. Powers of 2 are 1, 2, 4, 8, 16, 32, 64…etc. So you’re looping thru the while(j < number) statement. ‘j’ starts at 1, then goes to 2, then goes to 4, then 8 and so on until it is greater than ‘number’

3 Likes

Perfect, thanks. That clears it up, the wording of the problem was confusing me.