If I want to return a multiple values from a function, in an assigment, do I need to use an intermediate array to receive those values?
How am I used to do it in JavaScript:
let f = () => return [1, 2, 3];
let a, b, c, arr;
arr = f();
a = arr[0]; b = arr[1]; c = arr[2]
Is JavaScript like C, returning assignment to the first lhand operator, or is it possible to do something more flexible, like in this example from Ruby (without using loop):
def f
return 1, 2, 3
end
a, b, c = f
My motivation is simply lack of readability in the JavaScript method.
Issues
return not needed in simple arrow functionlet f = () => [1, 2, 3];
let [a, b, c] = f();
console.log(a, b, c)
You can get values from an array either using index or using destructuring . If there are multiple values then you can easily destructure and store it in different variables in a single statement.
let f = () => [1, 2, 3];
//Using Destructuring
const [a, b, c] = f();
console.log(a, b, c);
// Accessing using index
const arr = f();
const m = arr[0];
const n = arr[1];
const o = arr[2];
console.log(m, n, o);
Since you are using an array to return multiple values then you can use either implicitly return in a function of you can explicitly return an array from it
1) Explicitly return
let f = () => {
return [1, 2, 3];
};
const [a, b, c] = f();
console.log(a, b, c);
2) Implicitly return
let f = () => [1, 2, 3];
const [a, b, c] = f();
console.log(a, b, c);