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?

constとletのどちらを使うべきか

1
Posted at

はじめに

constとletのどちらを使用するべきなのか迷うことがあったので簡単にまとめます。

結論

const は定数であるため、再代入できない
let は変数であるため、再代入できる

迷ったら、const を使う!
後から再代入が必要になったときに let に変更!

const

const は「定数(constant)」を宣言するためのキーワードです。
一度値を代入したら、後から別の値を入れ直す(再代入する)ことができません。

const name = "田中太郎";
name = "佐藤花子"; // ❌ エラー!

なぜ const を使うのか?
プログラムの途中で勝手に値が書き換わるのを防げるため、コードの安全性が上がり、バグを減らすことができます。

let

let は変数を宣言するためのキーワードです。
後から何度でも新しい値を入れ直す(再代入する)ことができます。

let count = 1;
console.log(count); // 出力: 1

// 値を書き換える(再代入)
count = 2;
console.log(count); // 出力: 2

まとめ

基本は const を使う(意図しない再代入を防ぎ、安全性を高めるため)
再代入が必要な場合のみ let を使う(ループ処理や状態の更新など)

「基本は const、必要なときだけ let」と覚えておけば間違いありません!


最後まで読んでいただきありがとうございました!
少しでも参考になれば幸いです。

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?