With curly braces
const numbers = [1. -1, 2, 3];
let sum = 0;
for (let n of numbers)
sum = n;
console.log(sum)
the console printed the integer 5
Now, the curly braces have been added to the for loops
const numbers = [1, -1, 2, 3]
let sum = 0;
//for loops
for (let n of numbers){
sum = n;
}
console.log(sum)
the console printed the integer 3 instead
why?
CodePudding user response:
"= " isn't a valid operator, so the 2nd loop just sets sum to whatever n is in the current iteration. Since 3 is the last item in the iterated array, sum equals 3 after the loop completes.
CodePudding user response:
Either you wrote curly braces or not they are all the same only one difference is that only one statement can be written without curly braces and infinity with them;
the problem is in your code the first array is const numbers = [1. -1, 2, 3];
and the second is const numbers = [1, -1, 2, 3]