How to return multiple values in JavaScript

If there are multiple pieces of data that are logically related to each other, it makes sense to group them together and return them as a single unit.

JavaScript functions can only return a single value. However, you can use different ways to simulate returning multiple values, such as using arrays or objects.

When calling the function, you can use destructuring assignment to extract values from arrays or properties from objects and assign them to variables in a concise and readable way.

Using an array

JavaScript does not have a native tuple type like some other programming languages (e.g., TypeScript or Python). However, you can create tuple-like structures using arrays, but you have to rely on comments or external documentation to convey the meaning of each array element.

Using an array to return multiple values is a concise and straightforward way to package related data, especially if the data doesn’t need named properties. Arrays can hold various data types, including other arrays or objects. This flexibility allows you to return complex data structures when needed.

function getMultipleValues() {
  const value1 = 10;
  const value2 = "Hello";
  return [value1, value2];

const [value1, value2] = getMultipleValues();
console.log(value1); // 10
console.log(value2); // Hello

The order of elements in an array is crucial, and changes in the order can affect the meaning. This may lead to potential bugs if not handled carefully.

Using an object

Objects allow for more flexibility in terms of nesting and organizing data. You can give meaningful names to the properties, making it clear what each value represents.

function getMultipleValues() {
  const value1 = 10;
  const value2 = "World";
  return { value1, value2 };

const { value1, value2 } = getMultipleValues();
console.log(value1); // 10
console.log(value2); // World

It’s often a good practice to be consistent within your codebase. If most of your functions return objects, sticking with that convention. If you choose to return an object, use meaningful property names that convey the purpose of each value.

Ultimately, both approaches are valid, and the choice depends on the specific requirements and conventions of your project.

Returning objects in the context of API development is often considered a better practice for several reasons:

  • Object properties can have meaningful self-explanatory names.
  • Additional properties to be added in the future without breaking existing clients.
  • Returning objects is consistent with JSON (JavaScript Object Notation).
  • When an error occurs, you can include additional properties in the response object to provide details about the error, such as an error code, a human-readable message, or additional context.