telex-wap
telex-wap

Reputation: 852

Proper syntax to return variable and use it again (javascript)

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

Upvotes: 0

Views: 76

Answers (2)

Spencer Ruport
Spencer Ruport

Reputation: 35117

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.

Upvotes: 1

Korikulum
Korikulum

Reputation: 2599

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

var test = sum(2,2);

alert(test);

Upvotes: 2

Related Questions