JavaScript/予約語/const
表示
< JavaScript | 予約語
定数を定義する const
[編集]constキーワードは、定数を定義するキーワードです。定義するときに、値を入れる必要があります。入れなかった場合は、「undefined」が入れられます。
const price = 1500;
console.log('price = ' + price);
実行結果
price = 1500
定義後、letのように値を代入することはできません。なので、次のようなコードはエラーになります。
const price = 1500;
price = 400;
実行結果
Uncaught TypeError: Assignment to constant variable. at <anonymous>:1:7 (不明な型エラー: 定数への不正な代入。<anonymous>:1:7にて)
chromeのコンソールで実行(これからの実行結果もそうです)すると、上記の様になる。
const の配列
[編集]constの配列の作り方は、letのときと一緒です。
const array = ['index0', 'index1', 'index2', 'index3'];
console.log(array);
実行結果
(4) ['index0', 'index1', 'index2', 'index3']
0: "index0"
1: "index1"
2: "index2"
3: "index3"
length: 4
︙
const の配列は値の書き換えは可能ですが、代入はできません。