JavaScript | arguments と …rest の内部比較

JavaScript JavaScript
スポンサーリンク

では、argumentsスプレッド構文(...rest の内部的な違いを、図解+ブラウザ実験付きでわかりやすく説明します。


arguments vs ...rest の違い(内部挙動)

どちらも「関数に渡された引数をまとめる」仕組みですが、
中身の動き・性質がかなり違います。


まず結論から!

特徴arguments...rest
「配列のようなオブジェクト」✅ 完全な配列
strict mode での挙動引数と連動しない(独立)常に独立
非 strict mode での挙動引数とリンク(同期)常に独立
メソッド(map, filter など)❌ 使えない✅ 使える
名前付き引数との関係共有される(非 strict)無関係
モダンな書き方⚠️ 非推奨✅ 推奨(ES6)

内部挙動の違いを図で見る

非 strict mode の arguments

function sample(a) {
  console.log(arguments[0]); // 10
  a = 99;
  console.log(arguments[0]); // 99 ← 同じ実体を共有!
}
sample(10);
JavaScript
a ─┐
    │  同じ「値の箱」を指している
arguments[0] ┘

strict mode または …rest の場合

"use strict";
function sample(a, ...rest) {
  console.log(arguments[0]); // 10
  console.log(rest);         // []
  a = 99;
  console.log(arguments[0]); // 10 ← 別物
  console.log(rest);         // []
}
sample(10);
JavaScript
a → 値 10 (独立)
arguments[0] → 値 10(独立)
rest → []
(それぞれ別の箱)

💻 実際にブラウザで比較できる HTML 実験

以下を保存してブラウザで実行すると、
arguments...rest の動きがリアルタイムに比較できます👇

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>arguments vs ...rest 比較</title>
</head>
<body>
<h2>arguments vs ...rest の内部挙動比較</h2>
<button onclick="runNormal()">非 strict モード</button>
<button onclick="runStrict()">strict モード</button>
<button onclick="runRest()">...rest 使用</button>

<pre id="output"></pre>

<script>
function log(msg) {
  document.getElementById("output").textContent += msg + "\n";
}
function clear() {
  document.getElementById("output").textContent = "";
}

// 非 strict mode
function runNormal() {
  clear();
  log("【非 strict モード】");
  function test(a) {
    log("最初 a = " + a);
    log("最初 arguments[0] = " + arguments[0]);
    a = 99;
    log("変更後 a = " + a);
    log("変更後 arguments[0] = " + arguments[0]);
  }
  test(10);
}

// strict mode
function runStrict() {
  clear();
  log("【strict モード】");
  "use strict";
  function test(a) {
    log("最初 a = " + a);
    log("最初 arguments[0] = " + arguments[0]);
    a = 99;
    log("変更後 a = " + a);
    log("変更後 arguments[0] = " + arguments[0]);
  }
  test(10);
}

// ...rest 使用
function runRest() {
  clear();
  log("【...rest 使用】");
  function test(a, ...rest) {
    log("a = " + a);
    log("rest = [" + rest.join(", ") + "]");
    a = 99;
    log("変更後 a = " + a);
    log("rest = [" + rest.join(", ") + "]");
  }
  test(10, 20, 30);
}
</script>
</body>
</html>
HTML

🧪 試してみると次のようになります:

  • 非 strict
    aarguments[0] が連動して動く
  • strict
    → 独立(別の箱)
  • …rest
    → 完全に独立した配列として動く(map など使える)

まとめ(ポイント整理)

比較項目arguments...rest
構造配列風オブジェクト(Array ではない)本物の配列
要素と変数のリンク非 strict: あり / strict: なしなし
パフォーマンス若干遅い高速
モダンJSでの推奨度⚠️ 非推奨✅ 推奨
map/filter の使用❌ 不可✅ 可能

See the Pen arguments vs …rest comparison by MONO365 -Color your days- (@monoqlo365) on CodePen.

タイトルとURLをコピーしました