JavaScript では、ブロック スコープの変数を宣言するためにlet
キーワードが使用されます。ブロック スコープとは、変数が宣言されているコード ブロック内でのみ変数にアクセスできることを意味します。これは、関数スコープを持つvar
キーワードとは対照的です。 JavaScript でlet
を使用できるいくつかの方法を次に示します。
変数宣言:
JavaScript let x; // Declaring a variable named 'x'
変数の初期化:
JavaScript let y = 10; // Declaring and initializing a variable named 'y' with the value 10
ブロック範囲:
JavaScript if (true) {
let z = 5;
console.log(z); // z is accessible within this block
}
// console.log(z); // This would result in an error because z is not defined in this scope
ループの場合:
JavaScript for (let i = 0; i < 5; i++) {
// i is only accessible within this loop
console.log(i);
}
// console.log(i); // This would result in an error because i is not defined in this scope
同じスコープでの再宣言:
JavaScript let a = 3;
// let a = 5; // This would result in an error because a is already declared in this scope
シャドーイング:
JavaScript let b = 10;
if (true) {
let b = 5; // This 'b' shadows the outer 'b' within this block
console.log(b); // Outputs 5
}
console.log(b); // Outputs 10, the outer 'b' is not affected by the inner one
時間的デッドゾーン (TDZ):
JavaScript // console.log(tempVar); // This would result in a ReferenceError
let tempVar = 20; // The variable is declared but not yet initialized, it's in the TDZ until this line
console.log(tempVar); // Outputs 20
これらは、JavaScript でのlet
一般的な使用例です。 let
にはブロック スコープがあるため、11 で宣言された変数の可視性は、定義されているブロックに制限されることに注意することが重要です。