Table of contents #
getPersonalData function below runs, it returns a single string value for the
full name of a person.
function getPersonalData() const fullName = ‘John Doe'
Let’s say if you have the need to return multiple values from the
getPersonalData function like both the full name and age of the person how will you get it done?
Returning multiple values in Go lang #
In languages like Go lang, there is a possibility to return multiple values from a function, below is a code example with Go:
package main import "fmt" func getPersonalData() (string, int) return "John Doe", 24 func main() fullName, age := getPersonalData() fmt.Println(fullName) fmt.Println(age)
As you can see above, the function
getPersonalData returns two values. The first one is the string for full name and the second one is an integer for age. It is available on Go Playground if you want to fiddle around.
function getPersonalData() const fullName = 'John Doe'; const age = 24; return [fullName, age]; const person = getPersonalData(); console.log(`$person is $person years old.`);
As seen above, multiple (two) values have been returned from the
getPersonalData function wrapped in an array. A better and more expressive way of doing this with desctrcturing in JavaScirpt which will look like:
function getPersonalData() const fullName = 'John Doe'; const age = 24; return [fullName, age]; const [fullName, age] = getPersonalData(); console.log(`$fullName is $age years old.`);
If you notice the square brackets
[fullName, age], that is the destructuring part which makes naming the values on the first and second index of the array possible. So in the above code, the value on the first index is named
fullName and the value in the second one is named
age. These two well-defined variables make it very easy to understand the multiple values returned by the
Return multiple values using an object #
function getPersonalData() const fullName = 'John Doe'; const age = 24; return fullName, age; const person = getPersonalData(); console.log(`$person.fullName is $person.age years old.`);
You can see above the full name and age of
The same code using the power of destructuring to make it more eloquent and easier to understand is as follows:
function getPersonalData() const fullName = 'John Doe'; const age = 24; return fullName, age; const fullName, age = getPersonalDataObj(); console.log(`$fullName is $age years old.`);
Same as above the
fullName, age is used to destructure the object in this example. Here, the variable names match the property of the object which makes it easier to comprehend.
Code on JsFiddle #
Below is the running code example of Js fiddle, be sure to view the console on your browser to see the output of the code examples when you switch to the result tab: