Return Objects

As established in the functions chapter, JavaScript enforces a strict rule: a function can only return a single value.

When a function computes multiple pieces of distinct data, the standard practice is to package all of those values into an object and return that object.

Packaging Return Values

By combining object literals and the shorthand “No Colon” syntax, you can cleanly export multiple variables.

function doAllTheMath(x, y) {
  const sum = x + y;
  const difference = x - y;
  const product = x * y;
  const quotient = x / y;
  
  // Return a single object containing all four results
  return {
    sum,
    difference,
    product,
    quotient,
  };
}

const results = doAllTheMath(10, 5);

console.log(results.sum);        // 15
console.log(results.difference); // 5
console.log(results.product);    // 50
console.log(results.quotient);   // 2

This pattern is ubiquitous in modern JavaScript development for API data fetching and mathematical utilities.