JavaScriptの変数スコープ:グローバル、ローカル、モジュール

スコープは、変数を名前で読み書きできる範囲です。同じ実行環境ではグローバル名を複数のコードから使えます。ローカル名は宣言した関数やブロックと、その内側で使えます。

関数の内外で同じ名前を使う

最初の例では、関数内のmessageが外側の名前を隠します。これはシャドーイングです。内側の値を読んでも外側の値は変わりません。

const message = '外側';

function readInside() {
  const message = '内側';
  return message;
}

console.log(readInside()); // '内側'
console.log(message);      // '外側' 

新たに宣言せず関数から外側のletに代入すると、外側の変数が変わります。変更を呼び出し側で管理したい場合は、引数で値を渡し、結果を返します。

let total = 5;
function addOne() {
  total += 1;
}
addOne();
console.log(total); // 6

let・constとvarの違いを比べる

letとconstはブロックスコープです。例のvarは、ifの後でも同じ関数内なら参照できます。最後のmodernのコメントを外すとReferenceErrorになります。試した後にコメントを戻します。再代入が必要な場合はletを使います。

function checkBlock() {
  if (true) {
    let modern = 'ブロック内';
    var legacy = '関数内';
    console.log(modern); // 'ブロック内'
  }
  console.log(legacy); // '関数内'
  // console.log(modern); // ReferenceError
}
checkBlock();

クロージャがローカル変数を参照し続ける仕組み

クロージャは周囲のスコープにアクセスできる関数です。返された関数はcreateCounter()の終了後もcountを更新できます。作成関数を呼ぶたび別のカウンターになります。

function createCounter() {
  let count = 0;
  return () => ++count;
}

const next = createCounter();
console.log(next()); // 1
console.log(next()); // 2

クラシックスクリプトとモジュールを比較する

グローバル名がすべてグローバルオブジェクトのプロパティになるわけではありません。新しいページのクラシックスクリプトの最上位で宣言したvarはglobalThisのプロパティになります。letとconstは名前で参照できますが、プロパティは作りません。グローバル環境の規則を参照してください。

UTF-8のscript-scope.htmlとして保存し、ブラウザーのコンソールを開きます。最初のモジュールは1 2 3 4とtrue false false falseを出力します。次のモジュールでは名前が見えないのでundefinedになります。モジュール環境の規則を参照してください。コンソールに宣言を直接入力した場合は評価方法が異なることがあるため、HTMLで試します。

<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>スクリプトのスコープ</title>
</head>
<body>
<script>
var scopeDemoClassic = 1;
let scopeDemoLet = 2;
const scopeDemoConst = 3;
</script>
<script type="module">
var scopeDemoModule = 4;

console.log(scopeDemoClassic, scopeDemoLet, scopeDemoConst, scopeDemoModule); // 1 2 3 4
console.log(
  Object.hasOwn(globalThis, 'scopeDemoClassic'),
  Object.hasOwn(globalThis, 'scopeDemoLet'),
  Object.hasOwn(globalThis, 'scopeDemoConst'),
  Object.hasOwn(globalThis, 'scopeDemoModule')
); // true false false false
</script>
<script type="module">
console.log(typeof scopeDemoModule); // undefined
</script>
</body>
</html>

完全なサンプルでスコープと寿命を確かめる

scope-example.htmlとして保存し、開きます。内側と外側のラベルが異なります。増加ボタンを2回押すと、外側のラベルを変えずに2になります。リセットすると別のカウンターを作って0に戻します。

<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>グローバルとローカルのスコープを比較</title>
</head>
<body>
<h1>変数スコープを確認</h1>
<button id="increase" type="button">カウンターを増やす</button>
<button id="reset" type="button">リセット</button>
<pre id="output" aria-live="polite"></pre>
<script>
const label = '外側';

function labelInside() {
  const label = '内側';
  return label;
}

function createCounter() {
  let count = 0;
  return () => ++count;
}

let nextCount = createCounter();
let currentCount = 0;
const output = document.querySelector('#output');
function show() {
  output.textContent = `外側のラベル: ${label}\n関数内のラベル: ${labelInside()}\nカウンター: ${currentCount}`;
}

document.querySelector('#increase').addEventListener('click', () => {
  currentCount = nextCount();
  show();
});
document.querySelector('#reset').addEventListener('click', () => {
  nextCount = createCounter();
  currentCount = 0;
  show();
});
show();
</script>
</body>
</html>