LoginSignup
0
1

お母さんでもわかるJavaScript「const、分割代入、デフォルト値、スプレッド構文」

Last updated at Posted at 2023-03-21

constについて

constは基本、再宣言・代入ができない!
がしかし!代入や追加ができてしまうケースがある。それが「オブジェクト・配列・関数(他にも多分ある)」の時です。

※厳密には「その中身」を変えたり追加したりできる。変数自体を再代入することはできない。
(テキストノードやsrc、さらには要素も追加できる)

分割代入について

①分割代入を使用しない場合

index.js
const profile = {
    name:"清水",
    age:24,
};
const message = `私の名前は${profile.name}です。年齢は${profile.age}歳です。`;
console.log(message);

②分割代入を使用した場合

index.js
const {name,age} = profile;
const message = `私の名前は${name}です。年齢は${age}歳です。`;
console.log(message);

私の名前は${name}です。年齢は${age}歳です。
このように値を使うときに〇〇.〇〇と記述しなくていいから効率が良い!

デフォルト値の設定

デフォルト値とは引数などでよく使われる「もし指定したものがなかったら」のようなものです。
例えば、下記のように使用します!

index.js
//引数と指定した場合
const hello = (name) => console.log(`こんにちは${name}さん`);
hello("清水");//こんにちは清水さん

//引数と指定しなかった場合
const hello = (name) => console.log(`こんにちは${name}さん`);
hello();//こんにちはundefinedさん

//undefinedを防ぐために
const hello = (name = "ゲスト") => console.log(`こんにちは${name}さん`);
hello();//こんにちはゲストさん
hello("清水");//こんにちは清水さん

これを分割代入でも使えてしまうらしい!

index.js
const profile = {
    age:24,
};

//ダメなパターン
const{name} = profile;
const message = `こんにちは${name}さん`;
console.log(message);//こんにちはundefinedさん

//いいパターン
const{name = "ゲスト"} = profile;
const message = `こんにちは${name}さん`;
console.log(message);//こんにちはゲストさん

スプレッド構文

①要素の展開 各要素を個別の引数として関数に渡す。配列そのものではない。
②要素をまとめる
③要素のコピー、結合

index.js
const arr2 = [1, 2, 3, 4, 5];
const arr4 = [1, 2, 3, 4, 5];

//ノーマル
console.log(arr2);//[1, 2, 3, 4, 5]

//①
console.log(...arr2);//1 2 3 4 5

//②
const [num1 , num2 , ...arr3] = arr2;
console.log(num1);//1
console.log(num2);//2
console.log(...arr3);//3 4 5

//③
const arr3 = [...arr2];
console.log(arr3);//[1, 2, 3, 4, 5]

const arr4 = [...arr2,...arr4];
console.log(arr4);//[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

③のconst arr3 = [...arr2];const arr3 = arr2;でも実現可能ですが、予期せぬ挙動が出る場合があるので注意です。
どういうことかというと

index.js
//シンプルに代入する場合
const arr2 = [1, 2, 3, 4, 5];
const arr4 = arr2;

arr4[0] = 800;
console.log(arr2);//[800, 2, 3, 4, 5]→ あれ?arr2の中身も変わってる、、、
console.log(arr4);//[800, 2, 3, 4, 5]


//スプレッド構文で代入する場合
const arr2 = [1, 2, 3, 4, 5];
const arr4 = [...arr2];

arr4[0] = 800;
console.log(arr2);//[1, 2, 3, 4, 5] → こっちは影響されてない!
console.log(arr4);//[800, 2, 3, 4, 5]

なぜかというとconst arr4 = arr2;を代入しているわけではなく、「arr2はここに格納されてますよ〜」という情報のみが代入される仕組みになっているから。
つまり値が格納されているのはarr4ではなくarr2ってこと。
(むずかし、、、)

あとなんか適当にやってみた動き!

const numbers = [1,2,3];
console.log(numbers);//[1, 2, 3]

const [...newNumbers] = numbers;
console.log(newNumbers);//[1, 2, 3]

const {...NewNumbers} = numbers; 
console.log(NewNumbers);//{0: 1, 1: 2, 2: 3}
0
1
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
1