1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

varとlet、constの違いについて

1
Last updated at Posted at 2026-04-18

Javascript言語で変数の宣言でvarとletがあるが、
違いについて説明する。

let・const・var の違いは「再代入の可否」「再宣言の可否」「スコープ」「巻き上げ(hoisting)」の4点である。

一番実務で重要なのは 基本的に const、できるだけ letで変数を宣言して
var は使わない。

項目 var let const
再代入 〇 〇 ×
再宣言 〇 × ×
スコープ 関数スコープ ブロックスコープ ブロックスコープ
  • const:値が変わらないもの(基本これ)
  • let:値が変わる可能性があるときだけ
  • var:使わない(レガシーコード以外では不要)

  • var(関数スコープ)
if (true) {
  var x = 1;
}
console.log(x); // 1(外から見えてしまう)

→ ブロック {} を無視して外に漏れるので危険。

  • let / const(ブロックスコープ)
if (true) {
  let y = 2;
  const z = 3;
}
console.log(y); // エラー
console.log(z); // エラー

→ ブロックの外から見えないので安全。

  • const が基本推奨される理由
  • 再代入できないため、意図しない値の上書きを防げる
  • オブジェクトや配列は中身の変更は可能(再代入だけ不可)
const user = { name: "Han" };
user.name = "Lee"; // OK
user = {}          // エラー
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?