How to Return Multiple Values in JavaScript

Master different techniques to return two or more values from a JavaScript function using arrays, objects, and destructuring.

Introduction

In JavaScript, functions can only return one value—but that doesn’t mean you’re limited to a single piece of data. With a little structure, you can return two or more values cleanly and efficiently.

Let’s explore the most common and readable ways to return multiple values from a JavaScript function.

Using an Array

If the values you’re returning are related but don’t need labels, an array works great.

function getCoordinates() {
  const x = 10;
  const y = 20;
  return [x, y];
}

const [x, y] = getCoordinates();
console.log(x); // 10
console.log(y); // 20

Use when the returned values are ordered and you don’t need names.

Using an Object

Objects are perfect when you want to label your return values.

function getUser() {
  const name = "Alice";
  const age = 30;
  return { name, age };
}

const { name, age } = getUser();
console.log(name); // Alice
console.log(age);  // 30

Use when you want clarity, named properties, or flexibility with destructuring.

Returning a Class or Custom Type

For larger systems or reusable logic, you might return a class instance or a custom type.

class Result {
  constructor(success, data) {
    this.success = success;
    this.data = data;
  }
}

function fetchData() {
  // Simulate an API response
  return new Result(true, { id: 1, name: "Test" });
}

const result = fetchData();
console.log(result.success); // true
console.log(result.data);    // { id: 1, name: "Test" }

Use when working with structured data or patterns like Result<T> in TypeScript.

Returning Values with Promises

Async functions return Promises—but you can still return multiple values inside a resolved object or array.

async function getData() {
  return { count: 5, items: ["a", "b", "c"] };
}

getData().then(({ count, items }) => {
  console.log(count); // 5
  console.log(items); // ["a", "b", "c"]
});

Conclusion

While JavaScript functions can only return a single value, that value can be an array, object, or even a custom structure containing as many values as you need.

Choose the method that makes your code more readable, maintainable, and self-explanatory.

Want more dev insights like this? Subscribe to get practical tips, tutorials, and tech deep dives delivered to your inbox. No spam, unsubscribe anytime.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top