How to return multiple values from a JavaScript function

Last updated on May 27, 2021 by Suraj Sharma



In this tutorial, you’ll learn how you can return multiple values from a JavaScript function using Array destructuring and Object destructuring.

JavaScript functions do not support returning multiple values out of the box, but we can use a couple of hacks to get more than one value returned from a function.


There are two simple ways to do it,

  1. Store the values in an array and later return the array from the function or,

  2. Define an object with variable names as keys and values as values.


Example

function A() {
  const a = 1;
  const b = 2;

  return [a, b];
}

const [a, b] = A();
// a = 1 and b = 2;

// or

function B() {
  return { a: 1, b: 2};
}

const {a, b} = B();
// a = 1 and b = 2;

Next, whenever we call those functions we can use array destructuring or object destructuring to get multiple values from the called functions, as shown in the examples below.

Example 1

// using Array destructuring

function getSumAndMultiple (a, b) {
  const sum = a+b;
  const multiple = a*b;

  return [sum, multiple];
}

// calling the function

const [sum, multiple] = getSumAndMultiple(2, 3);

console.log(sum) // 5
console.log(multiple) // 6


Example 2

// using Object destructuring

function getSumAndMultiple (a, b) {
  const sum = a+b;
  const multiple = a*b;

  return {sum: sum, multiple: multiple}; // or simply, return { sum, multiple }
}

// calling the function

const { sum, multiple } = getSumAndMultiple(2, 3);

console.log(sum) // 5
console.log(multiple) // 6


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.