joni
joni

Reputation: 41

function return two values

I want to ask how effective is this function and if there are any situations when I can use it. Thanks for any answers.

function sum_and_dif(a, b) {
    var c = a + b;
    var d = a - b;
    return c +" " + d;
}

var result = sum_and_dif (200, 10);

document.write(result +"</br>");

var where_is_a = result.indexOf(" ");// Here i detected where is the empty space
var c_number = parseInt(result.substring(0, where_is_a));
var d_number = parseInt(result.substring(where_is_a +1,result.length));

document.write(c_number +"</br>");
document.write(d_number +"</br>");

Upvotes: 1

Views: 906

Answers (2)

deceze
deceze

Reputation: 522175

If you need to return more than one value, you're pretty much looking at an array or object:

function sum_and_diff(a, b) {
    …
    return { sum : c, diff : d };
}

var foo = sum_and_diff(1, 2);
alert(foo.sum);
alert(foo.diff);

Upvotes: 2

Nekresh
Nekresh

Reputation: 2988

It might be more useful to use an object as a return value, instead of a string.

return { sum: c, diff: d };

This way, you can easily use it by typing result.sum or result.diff.

Upvotes: 5

Related Questions