【JavaScript】変数のスコープが気になった

Uncategorized
138 words

気になった。

var

グローバル変数になる。

どこからでもアクセス出来る。

1
2
3
4
var test = 'hoge';
function onLoad() {
console.log(test); // 'hoge'
}

過去の遺産なので、使用は極力避けたい。

let

プライベート変数になる。

ブロック単位でしかアクセス出来ない。

1
2
3
4
5
6
7
8
9
10
11
12
var test1 = 'hoge1';
let test2 = 'hoge2';
function onLoad() {
var test3 = 'hoge3';
let test4 = 'hoge4';
console.log(test1); // 'hoge1'
console.log(test2); // 'hoge2'
console.log(test3); // 'hoge3'
console.log(test4); // 'hoge4'
}
console.log(test3); // 'hoge3'
console.log(test4); // アクセス出来ない

const

再代入不可能なプライベート変数になる。

1
2
3
4
5
function onLoad() {
const test = 'hoge1';
test = 'hoge2'; // エラー
}
console.log(test); // アクセス出来ない

参考サイト

https://qiita.com/masarufuruya/items/096e51c3e4c36c86ae27