In python, to return multiple variables, I can do --
def function_one(i):
return int(i), int(i) * 2
value, duble_value = function_one(1)
How would I achieve this same result using javascript if functions may only return a single return value? (I assume using an array?)
asked Apr 19, 2012 at 3:56
David542
112k211 gold badges584 silver badges1.1k bronze badges
2 Answers 2
You need to either use an array or an object.
For example:
function test() {
return {foo: "bar", baz: "bof"};
}
function test2() {
return ["bar", "bof"];
}
var data = test();
foo = data.foo;
baz = data.baz;
data = test2();
foo = data[0];
baz = data[1];
Sign up to request clarification or add additional context in comments.
5 Comments
Ateş Göral
Another option (but not as nice):
function test(ret) { ret.a = 42; ret.b = 43; }Ateş Göral
@pst This assumes someone intentionally passes in an object. This method has its uses, especially when you're collecting a set of parameters into the same pool (object) from multiple sources.
David542
What is the equivalent of a python dict,
{'a':'b', 'c':'d'}, called in js?Eric
@David542 Sometimes it is also called an associative array quirksmode.org/js/associative.html
function foo(){
return ["something","something else","something more","something further"];
}
let [a,b,c,d] = foo();
1 Comment
Peter Tutervai
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
lang-js
tuple-type so Objects (e.g.dict) or Arrays (e.g.list) can be used as a replacement. Also JavaScript doesn't have Sequence-unpacking (which makes thex, y = tuplepossible in Python) so the decomposition must be done long-hand.