+ 2
Please help to better explain this code to me in JavaScript
let result =1; let counter=0; while(counter<10){ result=result*2; counter=counter+1; } console.log(result) // 1024 why and how result output 1024 ,I don't understand, please can you clarify this to me
3 Answers
+ 11
The loop will run 10 times, each time multiplying the variable result by 2.
So we have:
result: 1 * 2 = 2
counter: 1
result: 2 * 2 = 4
counter: 2
result: 4 * 2 = 8
counter: 3
........
result: 512 * 2 = 1024
counter: 10
And now counter isn't smaller than 10 so the loop stops and result is printed. I hope I explained it well enough :)
+ 11
Glad you understood đ
+ 1
hey thank a lot , at first I never really understand the calculation you did there but when I took a closer look I understand though
the loop will run 10 time
first it will take the value
result =1*2=2 while counter=1
result=2*2=4 counter=2
result=4*2=8 counter=3
result=8*2=16. and so on
result=16*2=32
result=32*2=64
result=64*2=128
result=128*2=256
result=256*2=512
result=512*2=1024