0

//1st
 r = [2, 3, 7];
let sum = 0;
for (let a = 0; a <= 2; a++) {
    //let sum = 1;
    sum = sum + r[a];
    //console.log(sum);
}
console.log(sum);

//2nd
r = [2, 3, 7];
let sum = 0;
for (let a = 0; a <= 2; a++) {
    //let sum = 1;
    sum = sum + r[a];
    console.log(sum);
}
//console.log(sum);

//3rd
r = [2, 3, 7];
//let sum = 0;
for (let a = 0; a <= 2; a++) {
    let sum = 1;
    sum = sum + r[a];
    console.log(sum);
}
//console.log(sum);

hey I am confused between 1st & 2nd Vs 3rd when I declare let sum = 0 inside the for loop and outside the for loop. out come of these 3 codes are confusing please explain each of the following codes. I understood the logic behind 1st and 2nd code but the logic behind 3rd code confused me

  • If you have `let sum = 1` inside the `for` loop then it's declared each cycle and the value is set to `1`. So with the array `[2, 3, 7]` the expression ` sum + r[a]` produces `1 + 2`, `1 + 3` and `1 + 7` – VLAZ May 20 '22 at 06:59
  • Whats the difference between 2nd and 3rd code – Ayushman Chaturvedi May 20 '22 at 11:33
  • First difference `sum` is declared outside. Second difference `sum` is declared to be zero in 2. but one in 3. Third difference, the `console.log` is inside the loop. – VLAZ May 20 '22 at 11:35
  • 2nd is like let sum = 1; sum = sum + r[a], so, repeated 3 times like sum = 1 + 2 ; sum = 3 + 3; sum = 6 + 7 but 3rd is like let sum = 1 then sum = sum + r[a] so, sum = 1 + 2; sum = 1 + 3; sum = 1 + 7.. So here i understand how it happened but i couldn't understand logic behind these 2 i mean why it happened like this – Ayushman Chaturvedi May 21 '22 at 05:31

0 Answers0