Returning Objects and Arrays
What you'll learn: How to return objects and arrays from functions to pass back multiple related values at once.
So far, you've seen functions return single primitive values like numbers or strings. But what if you need to return multiple pieces of information from a function? You could call the function multiple times or use separate functions, but there's a much better way: return an object or array that bundles everything together.
Why Return Complex Data Structures?
Sometimes a function naturally produces several related values. For example, a function that analyzes text might need to return both the word count and the character count. Instead of choosing one or making two separate functions, you can return both in a single structure.
Think of it like a delivery truck: Instead of making multiple trips to deliver one item at a time, you load everything into one vehicle and make a single delivery.
Returning Arrays
Arrays work great when you have multiple values of the same type or when order matters:
function getMinMax(numbers) {
let min = Math.min(...numbers);
let max = Math.max(...numbers);
return [min, max]; // Return array with both values
}
const result = getMinMax([3, 7, 1, 9]);
console.log(result[0]); // 1 (min)
console.log(result[1]); // 9 (max)
Returning Objects
Objects are ideal when you want named properties for clarity:
function analyzeText(text) {
return {
words: text.split(' ').length,
characters: text.length,
firstWord: text.split(' ')[0]
};
}
const stats = analyzeText("Hello world");
console.log(stats.words); // 2
console.log(stats.characters); // 11
Key Takeaway: Return objects or arrays from functions to package multiple related values together, making your functions more powerful and your code cleaner.