5.3Destructuring / Multiple Return Values

複数の戻り値にはオブジェクトの分割代入

複数の値を返す場合は、配列の分割代入ではなくオブジェクトの分割代入を使用します。これにより、プロパティの追加や順序の変更が呼び出し元に影響を与えにくくなります。

配列で値を返すと、呼び出し側は `[left, right, top, bottom]` という順序を記憶しなければならず、将来的に戻り値の順序が変わったり、新しい値が追加されたりすると、呼び出し元のコードがすべて壊れてしまいます。オブジェクトで返せば、呼び出し側は `{ left, top }` のように必要なプロパティだけを名前で指定して受け取れるため、順序に依存せず、拡張性の高い堅牢なコードになります。

❌ Bad
// bad
function processInput(input) {
  return [left, right, top, bottom];
}
// the caller needs to think about the order of return data
const [left, __, top] = processInput(input);
✅ Good
// good
function processInput(input) {
  return { left, right, top, bottom };
}
// the caller selects only the data they need
const { left, top } = processInput(input);