0
0

javaScript 分割代入 デフォルト値 三項演算子

Last updated at Posted at 2023-11-09

分割代入

オブジェクトの場合

const myProfile = {
  name: "tami",
  age: "20"
  };
  
  const hello =`私の名前は${myProfile.name}です。年齢は${myProfile.age}歳です。`;
                
  console.log(hello);
私の名前はtamiです。年齢は20歳です。

これと同じものを分割代入で出力しようとすると

const myProfile = {
  name: "tami",
  age: "20"
  };
//波括弧の中にキー名を入れる、イコールの右側はどこからとってくるか
const {name,age} = myProfile;

const hello =`私の名前は${name}です。年齢は${age}歳です。`;
                
console.log(hello);
私の名前はtamiです。年齢は20歳です。

配列の場合

const myProfile = ["tami",20];
  
  const hello =`私の名前は${myProfile[0]}です。年齢は${myProfile[1]}歳です。`;
                
  console.log(hello);
私の名前はtamiです。年齢は20歳です。

これと同じものを分割代入で出力しようとすると

const myProfile = ["tami",20];
//配列の場合順番に注意する、設定する変数名は何でもよい
const [name,age] = myProfile;

const hello =`私の名前は${name}です。年齢は${age}歳です。`;
                
console.log(hello);
私の名前はtamiです。年齢は20歳です。

デフォルト値

関数を実行したとき、引数に値をとらない場合Undifinedになるため
それを解消するためにデフォルト値を設定することができる

//例えば以下のような関数があったとする
const hello = (name) => cosole.log(`こんにちは${name}さん!`);
//このとき引数に何も入れず関数helloを実行するとUndefindeになる
hello();
Undefined
//デフォルト値を設定するには引数に=でつないでデフォルト値を記述する
const hello= (name = "ゲスト") => console.log(`こんにちは${name}さん!`);
hello();
こんにちはゲストさん!

三項演算子

if,elseを一行で書けるようなそんなイメージ

let num = 5 ;
const result = num > 0 ? "OK!" : "自然数にしてね!";
console.log(result);
OK!
0
0
1

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