LoginSignup
0
0

More than 3 years have passed since last update.

プロゲート【JavaScriptⅢ 学習コース】関数の基礎

Last updated at Posted at 2020-10-31

prorate:JavaScript 学習コース Ⅲ

関数


// 関数の定義の仕方

const 定数名 = function(引数){
    // まとめたい処理
};

// 例

const introduce = function(){
    console.log("こんにちは");
    console.log("私はにんじゃわんこです");
};

introduce(); // 関数の呼び出し

// アロー関数 ES6から導入された書き方
function() = () => 


// 引数を使った例

const introduce = function(name){
    console.log("こんにちは");
    console.log(`私は${name}です`);
};

introduce("ニンジャワンコ");
introduce("ひつじ仙人");

複数の引数を受け取る関数の呼び出し


const introduce = function(name,age){ // コンマで区切る
    console.log("こんにちは");
    console.log(`私は${name}です`);
};

introduce("ニンジャワンコ",14); // コンマで区切る
introduce("ひつじ仙人",65);

戻り値


const add = (a,b) =>{ 
    return a+b ;
};

const sum = add(1,3);
console.log(sum);


const half = (number) => {
  return number / 2; // ()不要
};

const result = half(130);

console.log(`130の半分は${result}です`);


true falseの戻り値


const half = (number) => {
  return number % 2 === 0; // 2の倍数
};

console.log(check(6)); // true
console.log(check(7)); // false

returnの性質

※returnは、戻り値を返すだけでなく、関数の処理を終了させる性質も持っています。よって、returnの後にある関数内の処理は実行されない


const check = (number) => {
   return number % 3 === 0; // 3の倍数
};

// if文の条件式で、checkを呼び出す
if (check(123)) {
  console.log("3の倍数です");
} else {
  console.log("3の倍数ではありません");
}

関数の中の定数

関数の引数や、関数内で定義した定数や変数は、その関数の中でしか使うことができません。
下の図の場合、introduceの中で定義されている定数nameは、この関数の中でしか使うことができません。このようなそれぞれの定数や変数の使用できる範囲のことをスコープと呼びます。
一方、関数の外で定義した定数や変数は、関数の中でも使うことができます。
if文やwhile文でもスコープを作ります
-progate-


const name = "にんじゃわんこ"; // 関数外の定数

const introduce = (name) => {
  // 「わたしは〇〇です」を出力してください
  console.log(`わたしは${name}です`);

};

introduce("ひつじ仙人"); //関数内の定数


console.log(name); // 関数外の定数

総合演習


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


const getMax = (a,b,c) => {
  let max = a;

  if(max < b){
    max = b;
  }
  if(max < c){
    max = c;
  }

  return max;

}

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


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