0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptにはブロックスコープというものがあるらしい

Posted at

JavaScriptにはブロックスコープというスコープがあります。

const animal = [{name:"lion",cry:"gaooo"},{name:"horse",cry:"hihi-n"}]
for (let i = 0;i < 2;i++) {
  const name = animal[i].name;
  const cry = animal[i].cry;
  console.log(name);
  console.log(cry);
}

JavaScriptではconstは定数の定義に使われます。
nameやcryは再代入できない定数として定義されているので、2回目以降のループで上書きができなさそうですがそうはなりません。
波括弧{}で囲まれた範囲内がブロックスコープです。スコープ内で宣言された変数はその波括弧内からしか参照できません。

forループではくり返しごとに、新たなブロックスコープを作成するので
1回目と2回目のnameおよびcryは別のスコープとなるので問題が起きません。

C→COBOL→VB→Javaと変遷してきた私には、結構意外でした。

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?