Explain Codes LogoExplain Codes Logo

Return multiple values in JavaScript?

javascript
destructuring
return-multiple-values
async-patterns
Anton ShumikhinbyAnton Shumikhin·Mar 5, 2025
TLDR

A fast way to return multiple values in JavaScript, opt for using an array when order matters, or objects for named properties.

// Using array for values with an order function getSize() { return [width, height]; } // Here we go! Magic trick called destructuring const [width, height] = getSize(); // Using object to tag technique for values function getColors() { return { primary: 'blue', secondary: 'green' }; } // Also, surprise! Destructing works for objects too const { primary, secondary } = getColors();

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.

// Now hear me out...think of arrays like Yoda houses a list of values function getPoint() { return [x, y]; } const [x, y] = getPoint();

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:

// An object is like a small directory(don't mix it with the Windows directory) function getConfig() { return { host: 'localhost', port: 8080 }; } // Meet Obi-Wan Kenobi of JavaScript, Object destructuring! const { host, port } = getConfig();

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.

// Rename in action function getBounds() { return { xMin: 0, yMin: 10 }; } // Goodbye xMin and yMin, I rename you! const { xMin: left, yMin: top } = getBounds();

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:

// TypeScript typing function getSize(): [number, number] { return [1024, 768]; }

And, here's JSDoc's version:

/** * This function is like a magic mirror, tells the size no matter what! * @returns {{width: number, height: number}} */ function getSize() { return { width: 1024, height: 768 }; }

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?

// Promise returning multiple values as an object new Promise((resolve, reject) => { resolve({ success: true, payload: { user: 'Alice', token: 'abc123' } }); });

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