Heyy, could someone explain me, please, why power of 2 written this way? It doesn’t make sense for me why it’s j=j*2…
let j = 1;
while (j < number) {
j = j * 2;
}
The powers of two are 1, 2, 4, 8, 16, 32, 64, 128… and so on (doubling in the sequence). The line j = j * 2 is inside the while loop. It doubles j and assigns this new value to j every time the loop executes. So initially j = 1. Then this line executes:
j = j * 2.
After this j is assigned the value of 2. Next time in the loop j will be 4 and so on until the condition of the while loop (j < number) is no longer true. At this point the correct j value is “found” and it is entered into the array when while loop stops. You can also enter a console.log(j) inside the while loop to see what is happening as it can help with debugging and understanding.
2 Likes