Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return multiple variables from a JavaScript function?

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

like image 459
David542 Avatar asked Apr 19 '12 03:04

David542


People also ask

How do I return multiple variables from a function?

If we want the function to return multiple values of same data types, we could return the pointer to array of that data types. We can also make the function return multiple values by using the arguments of the function.

Can you return multiple variables in one method?

You cannot explicitly return two variables from a single function, but there are various ways you could concatenate the two variables in order to return them.

Can you return a variable from a function JavaScript?

JavaScript passes a value from a function back to the code that called it by using the return statement. The value to be returned is specified in the return. That value can be a constant value, a variable, or a calculation where the result of the calculation is returned.

Can you have a function return multiple values?

You can return multiple values from a function using either a dictionary, a tuple, or a list. These data types all let you store multiple values. There is no specific syntax for returning multiple values, but these methods act as a good substitute.


2 Answers

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];
like image 133
sberry Avatar answered Oct 15 '22 04:10

sberry


function foo(){
    return ["something","something else","something more","something further"];
}

let [a,b,c,d] = foo();
like image 3
uten Avatar answered Oct 15 '22 03:10

uten