This article explains how to return multiple values from a JavaScript function.
Is there a way to return multiple values from a function?
There are two ways to return multiple values: using arrays and objects, and using tables.
How to return multiple values from a function using arrays and objects
You can return multiple values by defining an array or object as the return value of a function .
If you want to return multiple values using an array, you can use the following code, for example.
function getValues() {
return [1, 2, 3];
}
const result = getValues();
console.log(result); // [1, 2, 3]
You can also use objects as well.
function getValues() {
return {
value1: 1,
value2: 2,
value3: 3
};
}
const result = getValues();
console.log(result); // { value1: 1, value2: 2, value3: 3 }
Sample imitating a tuple
In JavaScript, there is no concept of tuples, but you can achieve tuple-like behavior by returning an array containing multiple values .
For example, consider the following code:
function getValues() {
return [1, 2, 3];
}
const [value1, value2, value3] = getValues();
console.log(value1, value2, value3); // 1 2 3
Summary of this article
We explained how to return multiple values from a function.
- You can return multiple values from a JavaScript function by using arrays and objects.
- Arrays allow you to return an array containing multiple values.
- Objects allow you to return objects that contain multiple properties.
- Although the concept of tuples does not exist in JavaScript, you can achieve tuple-like behavior by returning an array containing multiple values.
Returning multiple values from a JavaScript function can be achieved using arrays, objects, and tuples.
You’ve created a function that returns multiple values!
It is important to choose a method that suits your data structure and usage.
Comments