Returning Multiple Values in JavaScript
📦 Why Return Multiple Values?
JavaScript functions can only return one value. However, that one value can be a structure like an Array or an Object, allowing us to effectively return multiple values bundled together. 🎁
Note
💡 Use arrays when order matters, and objects when naming each value is more meaningful.
📚 Method 1: Using Arrays
Arrays are ideal when the returned values are of the same type or order is important.
Returning Multiple Values as an Array
function getCoordinates() {
return [12.34, 56.78];
}
const [x, y] = getCoordinates();
console.log(x); // 12.34
console.log(y); // 56.78Note
🧠 Use array destructuring to extract the values cleanly!
📚 Method 2: Using Objects
Objects allow you to return multiple values with descriptive keys, making the code easier to read and maintain. 📘
Returning Multiple Values as an Object
function getUser() {
return {
name: "Alice",
age: 30
};
}
const { name, age } = getUser();
console.log(name); // Alice
console.log(age); // 30Note
💡 Object destructuring lets you grab values by key name regardless of order.
🧠 Choosing Between Array vs Object
| Approach | Use When... |
|---|---|
| Array | Values are positional and of the same type |
| Object | Each value has a unique meaning or label |
⚡ Real-World Use Case
Splitting a Full Name
function splitFullName(fullName) {
const [first, ...rest] = fullName.split(" ");
return {
firstName: first,
lastName: rest.join(" ")
};
}
const { firstName, lastName } = splitFullName("John Doe");
console.log(firstName); // John
console.log(lastName); // Doe🔗 Learn More
>>“The art of returning multiple values lies in clean bundling and smart unpacking.”