Reputation: 7631
Can a function return two values?
Can a function return two values? { I came across this in C} Any possibility of something in JavaScript
Upvotes: 3
Views: 317
Reputation: 236012
Not directly, but no one can stop you from returning an Array
with multiple elements:
function modify(a,b) {
return [a*2, b*2];
}
var res = multiple(5, 10);
console.log( res );
To push this a little further, we could use such a "mapped" result to call another method. Javascripts .apply()
comes in pretty handy for this.
function add(v1, v2) {
return v1 + v2;
}
and we could call
add.apply( null, modify(2,4) );
this effectively would be like
add(4, 8) // === 12
Upvotes: 5
Reputation: 270617
You can't return two distinct values but you can return an object or array. This is perfectly valid, as long as you document the behavior for anyone else who might encounter the code. It's helpful if the two returned values are truly related. If not, it can become difficult to understand the function. And just returning a diverse array of values from an object would be considered a bad practice by many people since a function's purpose is usually to perform a discrete action which may return a discrete value.
// As an object
function() {
return {val1: "value 1", val2: "value 2"};
}
// As an array
function() {
return ["value 1", "value 2"];
}
Upvotes: 6