0

I have this very simple thing, that doesn't work. What is happening? According to the tutorials that I have read, this should output 4...

function sum(a,b) {
    var result = a + b;
    return result;
    }

sum(2,2);        
var test = sum();

alert(test); // shouldn't this return "4"?

Link to the JSFiddle

3
  • sum(2,2) executes the function. var test = sum() assigns the result of sum without parameters, of course NaN. Commented Nov 7, 2012 at 0:06
  • sum(2,2) does return 4, sum() alone does return NaN - what did you expect (or: which tutorials did you read)? Commented Nov 7, 2012 at 0:06
  • I expected that var test = sum() would not run the function. Instead it would just retrieve the returned value. But then again, I have been studying javascript (and programming in general) mere few weeks. Commented Nov 7, 2012 at 0:14

2 Answers 2

2
function sum(a,b) {
    var result = a + b;
    return result;
}

var test = sum(2,2);

alert(test);
Sign up to request clarification or add additional context in comments.

Comments

1

Change this:

sum(2,2);        
var test = sum();

To this:

var test = sum(2,2);

The first code isn't technically wrong it just isn't doing what you're trying to do. You're calling the sum function with the appropriate values but never setting it's return value to any variable so it just gets thrown away. You seem to be under the impression that the value will "stick" to the function and this isn't the case. (Some BASIC languages can make it seem this way though. Perhaps that's where your misconception is coming from.)

Your second call is essentially the equivalent of

var test = sum(null, null);

and when you concatenate two null values you get null again.

7 Comments

No. undefined is not null, and both return NaN when summing them instead of null.
I realized that it looked strange to call the function without parameters, but... my very limited experience has shown me that when you do that: var test = sum(2,2) the function RUNS again, and I didn't want it to run, I just wanted to retrieve the value. That's why I was a bit confused.
@Bergi - I didn't feel like throwing a bunch of new terms at him.
@telex-wap - The function will run every time you call it. Functions have no inherent way of storing past values. That's what variables are for. :)
Yes, the only problem being, that if you store the returned value in a variable inside the function, you cannot use it outside... (or at least you cannot in the beginner level where I am. I guess there must be a way to get around that easily)
|

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.