LoginSignup
6
5

More than 5 years have passed since last update.

変数宣言const、letについてまとめてみた

Last updated at Posted at 2017-12-02

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

参考サイト

6
5
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
6
5