+ 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

31st Jul 2018, 12:25 AM
George S Mulbah II
George S Mulbah II - avatar
3 Respostas
+ 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 :)
31st Jul 2018, 12:51 AM
A Fox
A Fox - avatar
+ 11
Glad you understood 😊
31st Jul 2018, 1:19 AM
A Fox
A Fox - avatar
+ 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
31st Jul 2018, 1:17 AM
George S Mulbah II
George S Mulbah II - avatar