STUDY MEMO

学習のメモ書き

<javascript ES6> 関数、アロー関数、引数、戻り値、オブジェクトへの組み込み

 

関数とアロー関数

 

関数の定義は以下のコードで行う。

 

const 定数名 = function(){

 処理

};

定数名();

 

アロー関数はES6から導入された書き方で、

function()について、

() =>という記載で省略できる。

上記の定義に当てはめると下記のようになる。

 

const 定数名 = () => {

 //処理

};

定数名();

 

定義名を定義名()と書くことで、関数内の処理を実行できる(=関数の呼び出し)。

 

例:

const hello = function(){
 console.log("hello world");
}

hello();

 

関数と引数

引数を受け取る関数は以下のように書く。

 

 

const 定数名 = (引数名) => {

 //処理

};

定数名(値);  //値が引数に代入される

 

例:

const hello = (country) => {

 console.log("hello");

 console.log(`私は${country}出身です`);

};

hello("アメリカ");

hello("イギリス");

 

関数と戻り値

戻り値とは、呼び出しもとで受け取る処理結果(=関数が戻り値を返す)のこと。

以下のイメージ。

 

f:id:kabacho23:20200901205120p:plain

 

const 定数名 = () => {

 return 値;

}

 

return記載後の関数内の処理は実行されないので注意。

 

例:

const check = (number) => {
 return number % 2 === 0;
};

 

if (check(223)) {
 console.log("2の倍数です");
} else {
 console.log("2の倍数ではありません");
}

 

例:最大値を出力

const number1 = 103;
const number2 = 72;
const number3 = 189;


const getMax = (a,b,c)=>{
 let max = a;
 if(max <= b){
  max = b;
 } else if(c>=max) {
  max = c;
 }
 return max;
}


console.log(`最大値は${getMax(number1,number2,number3)}です`);

 

 

関数を使用したオブジェクト

 

オブジェクトは配列と同じく、複数のデータをまとめて管理することができる。

 

配列:[値1,値2,値3]

オブジェクト:{プロパティ1:値1,プロパティ2:値2}

 

 

関数はオブジェクトの値の部分に入れて使用することができる。

 

const 定数名 = {

 プロパティ名:() => {

  //処理

 }

};

定数名.プロパティ名(); //関数の呼び出し

 

 

例:

const food = {
 name:"卵",
 price:20,
  shop:() => {
   console.log("いらっしゃいませ");
   console.log(`${food.name}は1つ${food.price}円です。`);
  }

};
food.shop();