For loop sum in javascript 1

For loop sum in javascript

let sum = 0;
for (let i = 1; i <= 6; i++) {
    sum = sum + i;
}
console.log(sum)
//Output: 21

Here is what the above code is Doing:
1. We declare a variable sum and initialize it to 0.
2. We declare a variable i and initialize it to 1.
3. We check if i is less than or equal to 6. If it is, we execute the body of the loop.
4. We add i to sum.
5. We increment i by 1.
6. We go back to step 3.
7. When i is no longer less than or equal to 6, we exit the loop.
8. We log the value of sum to the console.

Similar Posts