Return multiple values in JavaScript?
A fast way to return multiple values in JavaScript, opt for using an array when order matters, or objects for named properties.
This magic trick is known as destructuring, use it to capture these values.
Destructuring: Unleashing the Magic
Ever felt like a magician using JavaScript? No? Well, I've got good news for you - destructuring is your magic wand in modern JavaScript. It gives you a way to unpack values from arrays or properties from objects without going through the old-school method of accessing them one by one.
The Great Debate: Arrays versus Objects
JavaScript offers two ways to return multiple values: arrays and objects. Just like choosing your favourite Star Wars episode, the choice entirely depends on the context:
Arrays are perfect for simple, fixed-size collections. Theirindeces are your guide to access the values.
On the contrary, Objects are your best friends when dealing with a larger or variable set of data where binary numbering (0, 1, 2..) doesn't make sense anymore:
The Array-Object Power Matrix
Object Power Up
While creating functions that return multiple values, thinking one step ahead can save your day. Objects makes it extremely easy to introduce new values without breaking the existing code. This is just like adding a new room to the already massive King's Landing Castle.
Unlocking Destructuring Power
Have you ever imagined renaming your variables while you access them? Well, programming isn't that hard! You can rename variables as you destructure.
The ES6 Revolution
Keep in mind that destructuring is the child of Symphony No. 6, i.e., ES6/ES2015. So sadly, for older JavaScript versions, you need to stick to plain old sequential access.
Strong allies: TypeScript and JSDoc
TypeScript or JSDoc users are bestowed with a neat syntax to denote the type signature of your function's return:
And, here's JSDoc's version:
Watch Your Steps!
Remember to avoid using comma-separated values as a return mechanism. Stick with arrays and objects, and keep in mind that mistakes may result in silent errors or a wild bug appearing!
Beyond Basics: Advanced Tactics
Unleashing the Power in Asynchronous Patterns
Transferring multiple values becomes more impressive with asynchronous code, such as Promises or async/await. Who said we can't return all relevant data in just one go?
Generators: Heroes Behind the Scenes
Generators and Iterators are not myths, they exist! They allow you to yield multiple values over time, perfect for managing large data streams or complex procedures.
References
Was this article helpful?