FAQ: Code Challenges: Intermediate JavaScript - Fix The Broken Code!

Let’s look at the initial code…

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
            i = 1;
            while (i < number) {
                  i = i * 2;
            }
            results.push(i);
      }
      return results
}

console.log(smallestPowerOfTwo(numbers)) 
// Should print the returned array [ 8, 4, 16, 32 ] instead prints the returned array [8]

Can you spot any errors, right off?

When we run the code above we get an SCT error (in the LE, not the console).

Your function should return an array with the power of two which is greater than the value of each number element in the array.

The output in the console shows,

[ 8 ]

That worked for me! Thanks! :pray:

If you don’t look for the solution in the code, you are not going to learn debugging. The answers are rarely found elsewhere. It’s our code. We should be able to spot the errors. In this case I’m saddened to see how many users admittedly look to the forums for the answer. This topic may have to be reviewed as a little too revealing at this critical stage.

Agreed! But in my defense, I didn’t just immediately go to the forums, scroll to your suggestion, and edit the code. I first spent around 30 minutes picking at the code (moved the code to VS Code, changing/moving brackets, adding/subtracting numbers, moving blocks up and down, etc) and parsing through stack overflow, MDN, other threads in the forums, youtube, etc. So, I think that I am teaching myself how to debug. Would you not agree?

1 Like

Yes and no. One of the greatest debugging techniques is not trial and error but reading the code bottom to top and looking for anomalies, things that don’t quite look right. This particular problem is solved just that way. Peering into the code without changing anything until the real culprit is spotted.

We are given the expected outcome, and also told what the present output will be. Therein lies the first clue. The program is running but not to completion. That means something is interrupting the program flow. It is clear there is something amiss in the loop(s). Debugging is about thought and understanding, not mechanics or seeing what works and what doesn’t, that’s tinkering.

Never tear a thing apart unless you want to start from scratch, again, which is probably the best thing to do in some cases. Start fresh and go over the steps more carefully, testing at every stage, which includes copious amounts of printing at each point to compare outputs with the expected values.

This problem is not one of those cases. We have a working program that doesn’t throw any errors. Knowing that means the problem is with the logic. Double face-palm if we’re the author and discover the error in this one. That’s the true debugging experience… Finding our own mistakes. Expect to make lots and lots of them so don’t get too confident in one’s self and be willing to face one’s errors with joy, not disdain.

Thank you for the thoughtful reply, I really appreciate it! At this point, I don’t have anyone to learn from other than things like this forum, educational software, and one developer friend who I don’t like to bother too much. I don’t know any of the processes or procedures that go into a real developers life. I look forward the day when I can go to meetups, etc.

1 Like

You’re welcome! We do our best here to tease people toward the problem/solution without flat out giving it away, save the odd time for mercy’s sake. It’s important to build up the experience of failure in this craft, and build up a knowledge base from that experience. We’d hate to rob someone of that so do our best to encourage as we coach. No matter the tone of what we are saying (especially me) the intent is there to lend a helping hand without taking away the challenge. Expect a lot of confusion as that is part of learning. Set frustration aside and don’t be afraid to fail, plan on it and then pick one’s self up and get back on the horse.

I’m having trouble with understanding how the second loop is accomplishing the math involved less than I am understanding what was causing the error.

The ‘inner’ while loop - searches for smallest power of 2 greater than the given number.


n = 1;
while (n < number) {
n = n * 2;
}
results.push(n);
}…

n = 1; iterated though n = n * 2 until n is no longer less than number; push the output of n = n * 2 into the new array.

is n = 1 increasing with each iteration of the while loop by 1? Similar to how i++ is in the for loop and the n++ is somehow implied? or is n becoming the value of n = n * 2 and then iterated through the while loop until n is no longer less than number?

No, n is increasing in powers of 2. First by 1, then by 2, then by 4, etc.

Yes, as suggested above. We are pushing successive accumulated values of n to the results array to arrive at corresponding values to the inputs.

[ 5, 3,  9, 30 ]
   \  \   \   \
  [ 8, 4, 16, 32 ]
1 Like

mind = blown

Thanks! :slight_smile:

1 Like

Hi all

After some time staring blankly the answer became quite simple. Ignoring all the mathematical complexities just look for a simple error in the for/while function. Just like block & global variables, i is represented in both the for and nested while loop (whereas we need the while loop to be treated separately. So in actual fact the only troubleshooting adjustment required is of the variable within the while loop, if I understood correctly.

1 Like

That is precisely how to approach debugging. Look for the obvious, or in this case not so obvious, and don’t change anything until you have gone over all the code down and up, checking each line. Looking for incongruence (shift in logic) comes next, as you have discovered. Once we find the thing that does not agree we have somewhere to begin fixing.

1 Like