So in the Code Challenges intermediate Javascript practice ‘Fix the broken code’ it asks to fix the code which i did. However, i would like if someone could help understand the code better. I understand the For loops and going through elements in an arrray. But, how the numbers = [5, 3, 9, 30] converts to number [8, 4, 16, 32] if in the while loops it says
let j = 1;
while (j < number);
results.push(j)
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];
console.log(number)
// The 'inner' while loop - searches for smallest power of 2 greater than the given number
let j = 1;
while (j < number) {
j = j * 2;
}
results.push(j);
}
return results
}
console.log(smallestPowerOfTwo(numbers))
// Should print the returned array [ 8, 4, 16, 32 ] instead prints the returned array [8]
We see that the first result greater than 5 is 8. The first result greater than 3 is 4. The first result greater than 9 is 16, and the first result greater than 30 is 32.
That makes a lot of sense but this does not make sense to me j = j * 2. Maybe i am mistaken that line of code as multiplication rather than as a exponent. is it just for javascript that works like that?
If you insert a bunch of of calls to console.log to write out what’s being done then you can read the output to see what happened.
Really though, you should be reading the code since that says what will happen. If you don’t know what something does - great, then you know what to look up. You can as just mentioned also study its effect by printing out your state before and after.
Yeah some things can be mysterious and difficult to look up, but what does * do? Probably something you can answer through observations, existing knowledge, and some googling.