How to send back multiple values from a JavaScript function?

Hey everyone, I’m working on a JavaScript project and I’ve hit a snag. I want my function to give back two different values, but I’m not sure if that’s even possible in JS. Here’s what I’ve tried so far:

function getStuff() {
  let firstThing = myObject.someProperty.value;
  let secondThing = myObject.anotherProperty.value;
  return firstThing, secondThing;
}

When I run this, it only seems to return the second value. Is there a way to make this work? Or do I need to rethink my approach entirely? Any help would be awesome!

I’ve run into this issue before, and there’s a neat trick I use that might help you out. Instead of trying to return multiple values directly, you can use a technique called ‘tuple packing’ in JavaScript. Here’s how it works:

function getStuff() {
let firstThing = myObject.someProperty.value;
let secondThing = myObject.anotherProperty.value;
return [firstThing, secondThing];
}

Then, when you call the function, you can use array destructuring to unpack the values:

const [value1, value2] = getStuff();

This approach is clean, efficient, and works well for functions that need to return a fixed number of related values. It’s especially useful in data processing or when working with coordinates or paired data. Just remember to document your function well so other developers (or future you) know what to expect from the return value.

hey tom, ur close! try returning an object or array instead. like this:

return [firstThing, secondThing];

or

return {first: firstThing, second: secondThing};

then u can grab both values when u call the function. hope this helps!

In JavaScript, returning multiple values from a function is indeed possible, but not directly as separate entities. The approach you’re looking for involves using data structures. A common and efficient method is to return an object. This allows you to encapsulate multiple values with descriptive keys:

function getStuff() {
  return {
    firstThing: myObject.someProperty.value,
    secondThing: myObject.anotherProperty.value
  };
}

You can then destructure the result when calling the function:

const { firstThing, secondThing } = getStuff();

This method provides clarity and flexibility, especially when dealing with multiple return values in larger projects.