23

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?)

3
  • 1
    Technically you're returning a tuple with two fields in it, which is still a single value. I'm not familiar with Javascript, but if there's some sort of array or structure that can be used, then that'd be ideal. Commented Apr 19, 2012 at 3:58
  • 3
    If the two integers you're returning are prime numbers, you can return their product. :P Commented Apr 19, 2012 at 3:59
  • 2
    Makoto's comment is a very good one. Python can only return one value as well. JavaScript doesn't have a 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 the x, y = tuple possible in Python) so the decomposition must be done long-hand. Commented Apr 19, 2012 at 4:02

2 Answers 2

43

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

Another option (but not as nice): function test(ret) { ret.a = 42; ret.b = 43; }
@AtesGoral That won't work when a "non-object" type is passed in (and will be a nasty exception if no params are supplied). It also makes me want to vomit a little.
@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.
What is the equivalent of a python dict, {'a':'b', 'c':'d'}, called in js?
@David542 Sometimes it is also called an associative array quirksmode.org/js/associative.html
4
function foo(){
    return ["something","something else","something more","something further"];
}

let [a,b,c,d] = foo();

1 Comment

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.

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.