In JavaScript, a function can technically only return one value. However, you can bypass this limitation by wrapping multiple values into a single Object or Array.
With the addition of Destructuring in modern JavaScript (ES6+), this process has become very clean and readable.
1. Returning an Array
Returning an array is best when the order of the values matters, or when the values don’t necessarily need “names.”
JavaScript
function getCoordinates() {
const x = 10;
const y = 20;
return [x, y]; // Returning multiple values as one array
}
// Using Array Destructuring to unpack the values
const [x, y] = getCoordinates();
console.log(x); // 10
console.log(y); // 20
- Best for: Simple pairs (like [latitude, longitude]) or hooks (like React’s useState).
- Downside: You have to remember the exact order when unpacking.
2. Returning an Object
Returning an object is the most common method. It allows you to give each value a name (key), making your code self-documenting.
JavaScript
function getUserData() {
return {
firstName: "Alice",
lastName: "Smith",
email: "alice@example.com"
};
}
// Using Object Destructuring to unpack
const { firstName, email } = getUserData();
console.log(firstName); // "Alice"
console.log(email); // "alice@example.com"
- Best for: Returning large sets of data or optional values.
- Benefit: The order doesn’t matter, and you can pick and choose only the variables you need.
3. Advanced: Using a Wrapper Object (The “Result” Pattern)
In professional development, you often need to return a Result and an Error simultaneously. This prevents the program from crashing if something goes wrong.
JavaScript
function fetchData() {
try {
// Logic to get data...
return { data: { id: 1 }, error: null };
} catch (e) {
return { data: null, error: "Connection failed" };
}
}
const { data, error } = fetchData();
if (error) {
console.error(error);
} else {
console.log(data);
}
4.Using the “Spread” Operator
Sometimes you might want to return many values but only capture a few specifically, leaving the rest in a separate group.
function getScores() {
return [95, 80, 75, 60, 40];
}
const [gold, silver, ...theRest] = getScores();
console.log(gold); // 95
console.log(theRest); // [75, 60, 40]
Which one should you use?
If you are returning two values that are logically a pair (like [width, height]), an Array is fine. For almost everything else, use an Object—it makes your code much harder to break if you decide to add more return values later.
5. Returning from a Closure
Combining what we learned about closures earlier, you can return multiple functions inside an object to create a “module.”
function createPlayer(name) {
let score = 0;
return {
getName: () => name,
getScore: () => score,
addPoint: () => score++
};
}
const player = createPlayer("Alice");
player.addPoint();
console.log(`${player.getName()} has ${player.getScore()} points.`);
// "Alice has 1 points."
