Using a For Loop Inside a Function Javascript


#1


Using the basic function given below, add code so that sum_odd_numbers will print to the console the sum of all the odd numbers from 1 to 3000. Don't forget to call the function!

I am getting the sum and then under it undefined. So
40677 //random numbers
undefined
How can I do this correctly and get rid of the undefined? Also the question is asking me to put var sum= 0 inside the function brackets but is that possible? I have it on top because that's the only way I can get it to work.

var sum = 0;
function sum_odd_numbers() {
    for (var i = 1; i < 3000; i += 2) sum += i;

    console.log(sum);
}
console.log(sum_odd_numbers(sum));


#2

That is a result of a logging console.log().

console.log(console.log());    // undefined

The fix would be to remove the statement from your function.

Yes, and recommended. It is a locally defined variable and sent as a return value.

var sum_odd_numbers = function () {
    var sum = 0;
    for (var i = 1; i < 3000; i += 2) {
        sum += i;
    }
    return sum;
}
console.log(sum_odd_numbers());

Note that since the function doesn't have any parameter we don't pass an argument. sum is declared locally so every time this function is run, it starts from zero. The return value is logged in calling scope, not function scope.


#3

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