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 3 years have passed since last update.

関数

Last updated at Posted at 2021-04-10

関数とは

  • 値を受け取って値を返すもの
  • ある一連の手続き(タスクや値計算)を再度利用できるようにまとめたもの

メリット

  • コード量の削減
  • 再利用可能
  • コードの見通しが良くなる

オブジェクトのメソッド=関数

構文

function 関数名(仮引数1,仮引数2) {
    //いろいろ処理
    return 関数の返り値;
}

文字数制限

function isTweetble(text) {
  return text.length <= 140;
}
console.log(isTweetble("foo")); //true

returnを使わない方法

function alertTweetble(text) {
  if (text.length <= 140) {
    alert("you can tweet!");
  }
}
alertTweetble("hoge");//you can tweet!

関数式

変数(定数)に関数を値として代入し、後からその変数を呼び出すことで関数を間接的に利用する方法

const isTweetble = function (text) {
  return text.length <= 140;
}

console.log(isTweetble("hoge"));//true

関数名は無くても動かすことができる(匿名関数)

コールバック関数

  • 引数に関数を入れたもの
  • 引数に関数を受け取った関数を高階関数という
  • それぞれの関数がコンパクトになり、役割が明確になる
function unfollow() {
  console.log("フォローを外しました");
}

function cancelTweet() {
  console.log("ツイートをキャンセルしました");
}

//確認を完了させる処理(コールバック関数)
function confirmed(fn) {
  if (window.confirm("実行しますか?"));
  fn();
}
confirmed(cancelTweet); 

アロー関数

const tax = (number) => {
  return number * 1.08;
}
tax(300);//324

変数に関数を代入する形にして、function(){...}() => {...}に変換

const isTweetble = (text) => {
  return text.length <= 140;
}
console.log(isTweetble("hoge"));//true
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?