LoginSignup
18
10

More than 3 years have passed since last update.

JavaScriptの変数巻き上げという概念

Posted at

普段は他の言語を使っているがJavaScriptに入門して変数の巻き上げという独特の概念に出会ったので、自分用のメモとしてその挙動を簡単にまとめておく。

変数が宣言されていない

const func = () => {
  console.log(hoge); // Error: hoge is not defined
};

func();

Error: hoge is not defined
そんな変数はない。まあ当然だよね。

変数を使用した後でconst(もしくはlet)で宣言されている

const func = () => {
  console.log(hoge); // Error: Cannot access 'hoge' before initialization
  const hoge = 'hoge';
};

func();

Error: Cannot access 'hoge' before initialization
え・・・。宣言されていないんじゃなくて? 初期化がされていないの?

内部的にはこう↓らしい。

const func = () => {
  const hoge;
  console.log(hoge); // Error: Cannot access 'hoge' before initialization
  hoge = 'hoge';
};

func();

変数を使用した後でvarで宣言されている

const func = () => {
  console.log(hoge); // undefined
  var hoge = 'hoge';
};

func();

undefined
今度も変数宣言はされているが、値は未定義という結果。
これはこう↓か。

const func = () => {
  var hoge;
  console.log(hoge); // undefined
  hoge = 'hoge';
};

func();

まとめ

他の言語であれば変数を使用するより前に宣言していないと宣言されていないというエラーになるところが、JavaScriptでは変数は宣言されているが値がないということになる。どこで宣言してもスコープ内の頭で宣言したのと同じ挙動になるので巻き上げというらしい。
とはいえ、値がなくてエラーになるので、結果だけ見れば他の言語とそう変わらないかも。

よくわからないのは、2つ目と3つ目の違い。初期化されていないのと値が未定義なのって何が違うんだ?

参考

JavaScript 変数の巻き上げと対策

18
10
2

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
18
10