JSBits #2: Return more than one value

Captain's log, stardate d67.y38/AB

Here's another JavaScript bits we wanted to share with you. Small tips and tricks for JavaScript developers for all levels. This time around, we share how to return more than one value.

Bright lights - Photo by Sigmund on Unsplash

Some programming languages implement the tuple data structure. It's (normally) a fixed length, immutable list, that has very good performance.

Tuples are used lot of times to return more than one value from a function.

It's a common and idiomatic pattern in Javascript to use Array destructuring for the same purpose:

function calculate(...) {
  // return the values wrapped into an array
  return [total, average];

function myBussinesLogic(...) {
  // destructure the array to obtain the values
  const [total, average] = calculate(...);

Happy destructuring!

Daniel Gómez

Daniel Gómez

Dani started playing with computers with his Oric 1, at least 100 years ago. He now juggles his programming skills with two bands and being a father of three. Legend says, it's him and his identical twin brothers working as a team.

comments powered by Disqus

You're one step away from meeting your best partner in business.

Hire Us