0

I've written the following simple JavaScript code. But whenever I run it, it displays "Undefined" as a result.

Following is the code:

function naturalSum(num1,num2) {
    var sumValue = 0;
    for (i=0;i<1000;i++)
    {
        if (i%num1 === 0 || i%num2 === 0) {
            sumValue += i ;    
        }
    }
}
document.write(naturalSum(3,5));

I want to know why this is happening. When I'm not enclosing the code within the function, the code's working fine. Kindly help me on this.

1
  • 2
    have you not posted the return call, or is that your problem Commented Mar 3, 2014 at 14:33

2 Answers 2

3

JavaScript functions return undefined by default, unless you explicitly return something.

So, if you want your function to return sumValue, you should add return sumValue; as the function’s last line:

function naturalSum(num1,num2) {
    var sumValue = 0;
    for (i=0;i<1000;i++)
    {
        if (i%num1 === 0 || i%num2 === 0) {
            sumValue += i ;
        }
    }
    return sumValue;
}

@AmitJoki created a JSFiddle to demonstrate:

Sign up to request clarification or add additional context in comments.

1 Comment

hi, I just created a fiddle, when your answer sprang up. can you include it please ? The url is jsfiddle.net/dgC46
1
function naturalSum(num1,num2) 
{
    var sumValue = 0;
    for (i=0;i<1000;i++)
    {
        if (i%num1 === 0 || i%num2 === 0) 
        {
            sumValue += i ;
        }
    }
    //You forgot to return the value
    return sumValue;
}
document.write(naturalSum(3,5));

4 Comments

Yup, problem solved. However, I have one more question. I used the return keyword with like this: function naturalSum(num1,num2) { var sumValue = 0; for (i=0;i<1000;i++) { if (i%num1 === 0 || i%num2 === 0) { return sumValue += i ; } } } document.write(naturalSum(3,5)); But then the editor was displaying an error that the return stating that the function does not always return a value. I want to ask that why is this happening?
@saadi123: I suspect it’s because you put your return statement within an if statement, so it’ll only get called when the if’s condition is true.
@Dennington-bear: this from Pedant’s Corner: a return statement outside the if but inside the for would make the function return the first time the for loop runs. It would never increment, because the return statement would have made the function return before it got a chance.
@PaulD.Waite Thanks for the guidance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.