ES6から変数宣言で「const」「let」が使えるようになりました。
自分のなかで、なぜ「var」ではなく「const」「let」を使った方がいいのかよく分からなかったのでまとめてみました。
Windowオブジェクトにプロパティを追加できない
グローバルスコープでconst(let)を変数宣言したとき、Windowオブジェクトのプロパティには追加されない。
varを使う
var scope = 'scope';
console.log(scope); // scope
var scope = 'scope';
console.log(window.scope); // scope
constを使う
const scope = 'scope';
console.log(scope); // scope
const scope = 'scope';
console.log(window.scope); // undefined
巻き上げを行うと「ReferenceError」になる
変数宣言する前にその変数にアクセスしようとしたとき、const(let)は「ReferenceError」になります。
varを使う
function fnc() {
console.log(scope); // undefined
var scope = 'scope';
}
fnc();
constを使う
function fnc() {
console.log(scope); // Uncaught ReferenceError: scope is not defined
const scope = 'scope';
}
fnc();
ブロックスコープの外からはアクセスできない
「if、else、for、for...in、while、switch」など「{}」(ブロック)内にconst(let)で変数宣言したとき、外からアクセスすることができない
varを使う
for (let i = 0; i < 10; i += 1) {
var scope = 'scope';
}
console.log(scope); // scope
constを使う
for (let i = 0; i < 10; i += 1) {
const scope = 'scope';
}
console.log(scope); // Uncaught ReferenceError: scope is not defined