What's the difference between these two codes? JS

function sumOfArray(array) {
var result = 0
for (i = 0; i < array.length; i++)
result += array[i]
return result
}
var numbers = [1,2,3];
sumOfArray(numbers);

it shows 6

function sumOfArray(array) {
for (i = 0; i < array.length; i++)
var result = 0
result += array[i]
return result
}
var numbers = [1,2,3];
sumOfArray(numbers);

this shows NaN

I’m just a beginner of JS please help!

When you use a for loop in Javascript put it in a bracket like so:

for (var i =0; i < array.length; i++) {
}

You’re running into scope issues due to not putting the for loop in brackets. The difference between the two examples involves the missing brackets and also where var result is defined.

1 Like

So it should look like this:

function sumOfArray(array) {
   var result = 0;
   for (i = 0; i < array.length; i++) {
    result += array[i];
   }
   return result;
}
1 Like

Make sure to declare your i variable in your for loop with a var or let.

Otherwise you will create a global variable.