Language/JavaScript

JavaScript~変数宣言 const、let、varの比較

NANCEEE 2023. 5. 31. 12:48
반응형

varを使った変数宣言

最近はあんまり使われてはいません。 変数の上書き(再割り当て)ができるし, 変数の再宣言ができます。この再宣言の可能性のせいで、安定性のため最近にはよく使われておりません。

var tmpVal = '宣言';
console.log(tmpVal);     // '宣言'を出力

tmpVal = '修正';
console.log(tmpVal);     // '修正'を出力

var tmpVal = '再宣言';
console.log(tmpVal);     // '再宣言'を出力

letを使った変数宣言

変数の再宣言ができない です。しかし、変数の上書き(再割り当て)はできます。 上書きが必要な変数の宣言に使われます。

let tmpVal = '宣言';
console.log(tmpVal);     // '宣言'を出力

tmpVal = '修正';
console.log(tmpVal);     // '修正'を出力

let tmpVal = '再宣言'; // errorが発生: Identifier 'tmpVal' has already been declared

constを使った変数宣言

変数の再宣言ができない し、 変数の上書き(再割り当て)もできません。 

const tmpVal = '宣言';
console.log(tmpVal);       // '宣言'を出力

tmpVal = '修正';           // errorが発生: tmpVal is read-only

const tmpVal = '再宣言';    // errorが発生: Identifier 'tmpVal' has already been declared

しかし、オブジェクト型のデータは場合、値の修正ができます。オブジェクト型には、オブジェクト、配列、関数などがあります。

オブジェクトの例

const obj = {
    name: 'Nancy',
    age: 30
};


console.log(obj.name); // 'Nancy'を出力

// プロパティーを修正 
obj.name = 'Paul';  
console.log(obj.name); // 'Paul'を出力

// プロパティーを追加 
obj.job = 'teacher';  
console.log(obj.job); // 'teacher'を出力

配列の例

const arr = ['Nancy', 'Paul'];

console.log(arr[0]); // 'Nancy'を出力

// 配列の要素の修正
arr[0] = 'Tom';  
console.log(arr[0]); // 'Tom'を出力

// 配列に要素を追加  
arr.push('Alice');  
console.log(arr); // ['Tom', 'Paul', 'Alice'] を出力

まとめ

特徴 var let const
変数の再宣言 × ×
上書き(再割り当て) △ (オブジェクト型のみ)
반응형