It is not possible to return multiple values in JavaScript. The solution is to return an array or, in EC6, destructuring assignments
.
// ⛔️ this is not possible in JavaScript
let treeAges = function () {
const oak = 8;
const maple = 12;
return oak, maple;
};
You can return an array with your values.
// 👇️ return an array
function getValues() {
return [getFirstValue(), getSecondValue()];
}
// 👇️ access the values
const values = getValues();
const firstValue = values[0];
const secondValue = values[1];
The destructuring assignment
syntax in EC6 is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
const [first, second] = getValues();
We can also "label" each of the return values by returning an object
. We can then reference each value by its name rather than its index.
// 👇️ create a 'labeled' object
function getValues() {
return {
first: getFirstValue(),
second: getSecondValue(),
};
}
// 👇️ access the values
const values = getValues();
const first = values.first;
const second = values.second;
// 👇️ access the values using ES6 syntax
const { first, second } = getValues();
It is not possible to return multiple values in JavaScript. The solution is to return an array or, in EC6, destructuring assignments
.
Related tutorials curated for you
ReferenceError: document is not defined in JavaScript
Returning multiple values in JavaScript
Cannot use import statement outside a module in JavaScript
Could not find module '@angular-devkit/build-angular'
Sort dates in JavaScript
Unexpected token u in JSON at position 0 Error