スコープ
メニューを表示するにはスワイプしてください
定義
スコープとは、変数にアクセスまたは使用できるコード内の領域。
スコープには2種類が存在:
- グローバルスコープ
- ローカルスコープ
変数がコードブロック(波括弧 {} の間)内で定義されている場合、その変数はローカルスコープを持つ。この場合、その関数やコードブロック、またはネストされたブロックの内部からのみアクセス可能:
123456789101112function exampleFunc() { let exampleVariable = 10; console.log(exampleVariable); // Valid if(10 + 10 == 20) { console.log(exampleVariable); // Valid } } exampleFunc(); console.log(exampleVariable); // Shows error
任意のコードブロック外で定義された変数はグローバルスコープを持ち、どこからでもアクセス可能:
123456789101112let exampleVariable = 10; function exampleFunc() { console.log(exampleVariable); // Valid if(10 + 10 == 20) { console.log(exampleVariable); // Valid } } exampleFunc(); console.log(exampleVariable); // Valid
下位(ネストされた)スコープで定義された変数は、上位(親)スコープからはアクセス不可:
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
注意
この例には、変数のスコープの仕組みを説明するために意図的なエラーが含まれています。コードを実行すると最初のエラーで処理が停止するため、このスニペットは説明のみを目的としています。
すべて明確でしたか?
フィードバックありがとうございます!
セクション 4. 章 4
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 4. 章 4