Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ スコープ | 関数の習得
JavaScript入門

bookスコープ

メニューを表示するにはスワイプしてください

Note
定義

スコープとは、変数にアクセスまたは使用できるコード内の領域。

スコープには2種類が存在:

  1. グローバルスコープ
  2. ローカルスコープ

変数がコードブロック(波括弧 {} の間)内で定義されている場合、その変数はローカルスコープを持つ。この場合、その関数やコードブロック、またはネストされたブロックの内部からのみアクセス可能:

123456789101112
function exampleFunc() { let exampleVariable = 10; console.log(exampleVariable); // Valid if(10 + 10 == 20) { console.log(exampleVariable); // Valid } } exampleFunc(); console.log(exampleVariable); // Shows error
copy

任意のコードブロック外で定義された変数はグローバルスコープを持ち、どこからでもアクセス可能:

123456789101112
let exampleVariable = 10; function exampleFunc() { console.log(exampleVariable); // Valid if(10 + 10 == 20) { console.log(exampleVariable); // Valid } } exampleFunc(); console.log(exampleVariable); // Valid
copy

下位(ネストされた)スコープで定義された変数は、上位(親)スコープからはアクセス不可:

function exampleFunc() {
  if (10 + 10 == 20) {
    let exampleVariable = 10;
    console.log(exampleVariable);
    // Output: 10
    // The variable is defined in this block, so it is accessible here
  }

  console.log(exampleVariable);
  // ReferenceError: exampleVariable is not defined
  // The variable was defined inside the if-block and is not accessible outside it
}

exampleFunc();

console.log(exampleVariable);
// This line will never execute because the script stops after the first ReferenceError
Note
注意

この例には、変数のスコープの仕組みを説明するために意図的なエラーが含まれています。コードを実行すると最初のエラーで処理が停止するため、このスニペットは説明のみを目的としています。

question mark

次のうち、変数のスコープに関する正しい記述はどれですか?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 4.  4

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 4.  4
some-alt