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?)
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.
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.
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.
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.
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];
function foo(){
return ["something","something else","something more","something further"];
}
let [a,b,c,d] = foo();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With