Destructuring Return Values from Functions
You'll learn how to unpack multiple values from a function's return array directly into separate variables in one clean line.
The Core Idea
When a function returns an array containing multiple pieces of data, you can immediately destructure that array right where you call the function. Instead of storing the entire array and then accessing elements by index, you extract the values into named variables all at once.
Think of it like receiving a gift box with multiple items inside. Rather than taking the whole box, setting it down, then removing items one by one, you can unpack everything directly as you receive it.
How It Works
function getCoordinates() {
return [42, 71];
}
// Without destructuring (more steps)
const coords = getCoordinates();
const x = coords[0];
const y = coords[1];
// With destructuring (cleaner!)
const [x, y] = getCoordinates();
console.log(x); // 42
console.log(y); // 71
Real-World Example
function getUserData() {
return ['Alice', 28, 'Engineer'];
}
const [name, age, profession] = getUserData();
console.log(name); // 'Alice'
console.log(age); // 28
console.log(profession); // 'Engineer'
You can skip unwanted values or use defaults just like regular destructuring:
function getStats() {
return [100, 85];
}
const [score, , bonus = 10] = getStats();
console.log(score); // 100
console.log(bonus); // 10 (default, since third element doesn't exist)
Key Takeaway: Destructuring function return values lets you unpack arrays returned from functions directly into named variables, making your code cleaner and more readable by eliminating intermediate steps.