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 1 year has passed since last update.

【JavaScript】var let const の違い

Last updated at Posted at 2022-12-11

はじめに

初めての投稿です.お手柔らかに...

Javascriptの変数宣言である var let constの違いについての備忘録。

  • varは使っちゃいけないって聞いたような...
  • とりあえず全部constでいいやろ!

このようになんとなくで宣言していたので具体的な違いについてまとめます。

何が違うの?

具体的に3つの違いを見ていきましょう。

var let const
再宣言 不可 不可
再代入 不可

再宣言

なぜvarを使う場面を無いかというと再宣言できてしまうからです。

declarations.js
//var
var num = 0;
var num = 1;
console.log(num);
// 出力結果: 1

//let
let num = 0;
let num = 1;
console.log(num);
// 出力結果: Uncaught SyntaxError: Identifier 'num' has already been declared

//const
const num = 0;
const num = 1;
console.log(num);
// 出力結果: Uncaught SyntaxError: Identifier 'num' has already been declared

このように一度宣言したvarを再宣言した場合、後から宣言した変数が適用されてしまいます。
これは意図しないバグの発生に繋がってしまいます。
letconstで宣言した変数を再宣言した場合はエラーになっていることが分かります。

再代入

続いて再代入の可、不可の違いを見ていきます。

assignment.js
//var
var num = 0;
num = 1;
console.log(num);
// 出力結果: 1

//let
let num = 0;
num = 1;
console.log(num);
// 出力結果: 1

//const
const num = 0;
num = 1;
console.log(num);
// 出力結果: Assignment to constant variable

このようにvarletでは一度宣言した変数に対して再代入を行うことができます。
constではエラーとなっていることが分かります。

ただしconstで宣言されたオブジェクトや配列のプロパティは変更することができます。

property.js
const profile = {
name: "taro",
age: 28
};
profile.name = "ziro";
profile.age = 26;
profile.addres = "Shiga";
console.log(profile);
// 出力結果: {name: "ziro", age: 26, addres: "Shiga"}

const animal = ["dog", "cat"];
animal[0] = "bird";
val5.push("monkey");
console.log(animal);
// 出力結果: ["bird", "cat", "monkey"]

結論

  • varは再代入も再宣言も防げないため使わない
  • 再代入が必要な場合はletを使う
  • 基本はconstを使う
    constしか勝たん!
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?