LoginSignup
1
0

More than 5 years have passed since last update.

JS初心者のメモ:Javascript関数

Posted at

Javascriptに於いて関数はとても重要なコンセプト。他の言語とは異なる特徴や使い方を持つ。まず初めに関数定義にもいくつか方法があるので紹介したいと思います。

Function declaration

function logMemo(memo) {
   console.log(memo);
}

もっともシンプルな定義の仕方。functionキーワードの後に関数名、カンマ区切りでパラメータを定義、そして{}内に処理を入れる。同ステートメント内に定義以外のステートメントは入れられない。他の言語でも使われている定義の仕方。

Function expression

document.body.addEventListener('click', function() {
    console.log('Clicked!');
})

return function() {return true;};

または

var myFunc = function() {};

これらをfunction expressionと呼ぶ。Function declarationとの大きな違いは別ステートメント内に存在することだ(return ステートメント内に定義されてるなど)。またfunction declarationと違って関数名がオプショナル。

Arrow function

ES6からarrow functionが登場しました。fat arrow(=>)と飛ばれるオペレータを使うことで関数をより端的に定義することが可能です(他にも利点はある)。

// パラメータなし
var func1 = () => console.log('Func1');
// パラメータが一つ
var func2 = message => console.log(message);
// パラメータが二つ以上
var func3 = (message1, message2) => console.log(message1+message2);
// 処理がブロックコードの場合
var func4 = (message1, message2) => {
    var message = message1 + message2;
    return message;
}
1
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
1
0