0
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?

More than 5 years have passed since last update.

varとletとconstの違いメモ

0
Posted at

自分的なメモです。
varとletとconstの違いを説明してみろと言われた時のための

  • varはES6より前で使われていた宣言方法。
  • letとconstは、ES6から採用された、新しい宣言方法。

再宣言、再代入に関する違い

var

再宣言、再代入が可能。


//再代入できる
var hoge = 'りんご';
hoge = 'みかん';

console.log(hoge); // 結果:みかん

// 同じ変数名を使って別のデータを再宣言できる
var hoge = 'すいか';

console.log(hoge); // 結果:すいか

let

letは代入し直すことはできるけど、同じ変数名を使って別のデータを再宣言するとエラーが出る。


// 再代入できる
let hoge = 'りんご';
hoge = 'みかん';

console.log(hoge); // 結果:みかん

let hoge = 'すいか';

console.log(hoge); // 結果:シンタックスエラー

再宣言はできないので

Uncaught SyntaxError: Identifier 'hoge' has already been declared
っていうシンタックスエラーが出ますよ

const

constは変数の中でも一番厳格で、再代入も再宣言もできない。constのことを変数ではなく「定数」と定義する場合もある
一度しか代入できないので、長いプログラムを書いた時に変数名が被らない。


// 再代入できる
const hoge = 'りんご';
hoge = 'みかん';

console.log(hoge); // 結果:シンタックスエラー

const hoge = 'すいか';

console.log(hoge); // 結果:シンタックスエラー

こちらもシンタックスエラー
Uncaught SyntaxError: Identifier 'hoge' has already been declared
が出ます

スコープの違い

var,let,contはそれぞれ影響範囲(スコープ)が異なります。

varの場合

関数スコープなので、関数の外にある変数に格納されているデータを関数内で出力することができません。

var hoge = 'りんご';
console.log(hoge); // 結果:りんご

function fugafuga(){

  console.log(hoge); // 結果:エラー
  
  var hoge = 'みかん';
  console.log(hoge); // 結果:みかん
}
fugafuga();

letの場合

  • 関数の外から呼び出すことは可能。外から呼び出した値を上書きすることもできる。
  • だけど再宣言は禁止されているのでエラーがでる
  • if{}やfor{}内で宣言したらその中でしか使用できなくなるブロックスコープなので、影響範囲が少なくなる
let hoge = 'りんご';
console.log(hoge); // 結果:りんご

function fugafuga(){

  console.log(hoge); // 結果:りんご

  hoge = 'みかん';
  console.log(hoge); // 結果:みかん
  
  let hoge = 'みかん';
  console.log(hoge); // 結果:Uncaught ReferenceError: Cannot access 'hoge' before initialization 

}
fugafuga();

constの場合

  • 関数の外から呼び出すことは可能。
  • 再代入もできず再宣言もできないのでエラーがでる。より厳格に定数内に収められた値を扱うことができる。
  • if{}やfor{}内で宣言したらその中でしか使用できなくなるブロックスコープなので、影響範囲が少なくなる
const hoge = 'りんご';
console.log(hoge); // 結果:りんご

function fugafuga(){

  console.log(hoge); // 結果:りんご

  hoge = 'みかん';
  console.log(hoge); // 結果:Uncaught TypeError: Assignment to constant variable. 
  
  const hoge = 'みかん';
  console.log(hoge); // 結果:Uncaught ReferenceError: Cannot access 'hoge' before initialization  

}
fugafuga();

とりとめのない感じになったけど、頭の中では整理できたので良しとする。
結論としては、今後はvarできるだけ使わないほうが良いよということでしょうか。以上です。

0
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
0
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?