0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

jsの関数巻き上げについて

Last updated at Posted at 2021-01-17
var myname = "global";
 
function func() { //1
    console.log(myname);    //undifined ///2
    var myname = "local";
    console.log(myname);    //local
}
 
func();

jsによってvar mynameだけが関数の先頭である1と2の間で実行される

宣言をletにすると

let myname = "global";

function func() {
    console.log(myname);    //ReferenceError: Cannot access 'myname' before initialization
    let myname = "local";
    console.log(myname);    //エラーで実行されない
}
 
func();

このようになり関数の巻き上げを防ぐことが出来る。
だからES6のletconstを使って宣言するべきなのかと

参考
https://developer.mozilla.org/ja/docs/Glossary/Hoisting
https://analogic.jp/hoisting/

0
1
1

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?