How to Return Multiple Values from a Function in JavaScript
Table of Contents
In JavaScript, you can only return one value from a function.
This is usually fine in most cases, but in other cases, you might need to return multiple things, like for example a success boolean and a status message.
In this post, we'll learn how to return multiple values from a function in JavaScript.
Returning Multiple Values from a Function
Let's say you're writing an API and you want to return a success boolean indicating if the request was successful or not, and a status message.
Usually, you'd have to do something like this:
JAVASCRIPTconst getSuccess = () => {
return true;
}
const getMessage = () => {
return "Success!";
}
const success = getSuccess();
const message = getMessage();
// do something with success and message
However, the problem with this is that the operation might need to be performed multiple times as the message might rely on the success boolean.
Instead, we can try returning an array:
JAVASCRIPTconst getSuccess = () => {
// perform operation here
return [true, "Success!"];
}
const [success, message] = getSuccess();
// do something with success and message
By taking advantage of array destructuring, we can set the values of both the success boolean and the message in one line, thereby simulating a function that returns multiple values.
This also works when using an object:
JAVASCRIPTconst getSuccess = () => {
// perform operation here
return {
success: true,
message: "Success!"
};
}
const { success, message } = getSuccess();
// do something with success and message
Instead of array destructuring, we're using object destructuring, and it accomplishes the same task as before.
Conclusion
In this post, we looked at how to simulate returning multiple values from a single function.
Simply take advantage of either array destructuring or object destructuring to set multiple variables from a single return.
Thanks for reading and happy coding!
- Getting Started with TypeScript
- Getting Started with Svelte
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- Getting Started with Deno
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API
- How To Create a Modal Popup Box with CSS and JavaScript