For loop need expanation

Iknow it is simple but I can’t figure it out…
code is

let number = 1;
let sum = 0;

for (let number = 1; number < 11; number++){
   sum += number;
}
console.log(sum);
´´´
and sum is 
0
3
6
10
15
21
28
36
45

while number is less then 11; i++ and sum = number + number
it should be if number is 1 goes 1++ that is 2 and number + number = 2 + 2 = 4
another iteration, 4++ = 5, 5+5 = 10 sum = 10 + 10 = 20,  how it goes I dont get it...??
1 Like

Not quite,

sum += number;

means

sum = sum + number

Try it this way:

let number = 1;
let sum = 0;

for (let number = 1; number < 11; number++){
   console.log('number before:', number);
   console.log('sum before:', sum);
   sum += number;
   console.log('sum after:', sum);
}
console.log(sum);

thank you!! I was thinking that sum += number means sum = number + number

1 Like

Just know, if you declare a local variable(variable declared inside parentheses {…}), then, when the code inside parentheses({…}) gets executed, it is going look for data in the local scope(anything inside parentheses {…} will always have a local scope means you can’t extract local data from outside the parentheses ) first and once it finds, it’s gonna use the value of the local variable and won’t even care what’s outside the local scope(means outside the parentheses {}) but if the variable isn’t declared inside the local scope then it will move to the outer scope to find it.
Hope that helps.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.