+ 1

Could someone please explain me this code? This is javascript

var sum = 0; for ( i = 4; i < 8; i++) { if ( i == 6) { continue; }; sum += i; }; document.write (sum);

1st Dec 2016, 8:00 PM
Andrés Amaya
Andrés Amaya - avatar
4 Antworten
+ 3
1. Starting with i=4 2. If i is less than 8 continue to step 3, else go to step 6. 3. if i is equal to 6, skip to step 5. 4. add i to the sum 5. increment i and go to step 2. 6. Print the value of sum to the document So...sum=4+5+7=16.
1st Dec 2016, 8:15 PM
kbyte
kbyte - avatar
+ 2
It is a loop, adding each number between 4 and 7 (The var keyword is missing before "i = 4", in the for). It just don't add the number if it is equals to 6. (There is not semi-colon after braces of any statement, you can remove them) continue keyword skips the rest of inscription in the loop to straight do i++ and pass to the next turn of the loop.
1st Dec 2016, 8:17 PM
Volts
Volts - avatar
+ 2
thank you, guys
12th Dec 2016, 9:49 PM
Andrés Amaya
Andrés Amaya - avatar
0
A variable named sum is assign a value of 0. This for loop, which has been inialized to 4 checks if i is equal to 6 and adds 1 to i each time the loop runs through. If i equals to 6 the program executes the block inside the if loop. The 'continue' block inside the if statement forces the for loop to end and executes the first line after the for loop. The current value of sum 0, is added to 1 and assigned to sum so sum is nowe of is now. i is the also increased by 1 so it now equals 5. The loop now goes back to the top with the updated vakues and runs through the loop again. The if compares i to 6 again skips the continue again because 5 is not equal to 6. sum = 2 and i = 6 at the end of the loop. This is where the magic happens. The if statement compares i to 6 once more. This time i is equal to 6 so the block in the if statement is executed. The continue insude the if statement forces the for loop to end. The next line outside of the for loop prints the value of sum which should be 2. Sorry. Made an error. the vakue of i is added to the current value of sum on every loop. sum = 4 at the end if the first loop. sum = 9 after the second one. sum = 15 on the third iteration. Tyoing on a Android device and can't see the code above.
1st Dec 2016, 8:21 PM
Jacques Navarro
Jacques Navarro - avatar