LoginSignup
1
0

More than 1 year has passed since last update.

【javascript】ループ分とブロックスコープ

Posted at

ブロックスコープ内のconst挙動について

case1

  • const変数は上書きできないが、ブロックスコープ内で上書きできているような挙動になっている。
  • 厳密にいうと、上書きではなく1ループごとに内部的異なる変数として評価されている。

for(let i = 0; i < 5; i++){
    const j = i * 2;
    console.log(j)
}

>>> 0
>>> 2
>>> 4
>>> 6
>>> 8

case2

  • setTimeoutをしようして1秒後にjを出力する。
  • 変数はvarを使用する。
  • 8が5回出力された。
for(let i = 0; i < 5; i++){
    var j = i * 2;
    setTimeout(function(){
        console.log(j)
    }, 1000)
}
>>> 8

なぜか?

  • varはブロックスコープをとらない
  • setTimeoutで1秒後に出力されている間に、var j = i * 2;が5回処理されて、処理の最後、すなわち8が5回出力されることになる。

以下の書き方と同じような結果になる。


var j;

for(let i = 0; i < 5; i++){
    j = i * 2;
    setTimeout(function(){
        console.log(j)
    }, 1000)
}

>>> 8
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0