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 1 year has passed since last update.

JavaScript入門 その4:関数

Last updated at Posted at 2023-11-08

JavaScript入門の書籍を読んで書いてあったこと+自分で調べたことのメモ書きその4。関数。

関数

関数の定義の方法としてアロー関数式とfunctionキーワードを使う方法があるが。差異について詳細は参考ページの2番目のページを参照。

アロー関数式

アロー関数式を右辺に記述し、左辺の変数に代入して関数を定義する。

下記の例では第2引数yにはデフォルト値がある。
getPosisonText は関数が代入された変数なので、テンプレートリテラル内でサンプルコードの最後の行のように関数を呼び出すことができる。

let getPointText = (x, y = 0) => {
  return `x座標:${x},y座標:${y}`
}

let str1 = getPointText(1, 2);
console.log("位置: " + str1);
console.log("位置: " + getPointText(5));
console.log(`位置: ${getPointText(3, 8)}`);

【実行結果】

位置: x座標:1,y座標:2
位置: x座標:5,y座標:0
位置: x座標:3,y座標:8

function記法

アロー関数式の他に、function記法により関数を定義することができる。む
下記の例の func1 の関数宣言の方法(function文)では無名関数を作ることはできない。
func2 の関数宣言でイコールの右辺はfunction式と呼ぶ。

function func1(a, b) {
  return a + b;
}

let func2 = function (a, b) {
  return a + b;
}

console.log(func1(1, 2));
console.log(func2(3, 4));

【実行結果】

3
7

残余引数

関数定義において最後の仮引数の前に ... を記述するとその仮引数の値はその仮引数の位置以降のすべての実引数を要素とする配列となる。これを残余引数という。残余引数により可変長引数の関数を定義することができる。

let introduceFriends = (name, ...friends) => {
  for (let friend of friends) {
    console.log(`${friend}${name}の友達です。`);
  }
}

introduceFriends("ジョン");
introduceFriends("マイケル", "一郎");
introduceFriends("ボブ", "一郎", "次郎", "太郎");

【実行結果】

一郎はマイケルの友達です。
一郎はボブの友達です。
次郎はボブの友達です。
太郎はボブの友達です。

関数を引数として渡す

関数を引数に取る関数がある。
下記は配列(Array)のメソッド filter()map() で関数を引数として渡すサンプルである。いずれも引数として無名関数を渡している。

例:

let outerPlanets = ["Jupiter", "Saturn", "Uranus", "Neptune"];
let result = outerPlanets.filter((planet) => planet.length > 6);
console.log(result);

【実行結果】

['Jupiter', 'Neptune']

例:

let numbers = [1, 2, 3];
let result = numbers.map((num) => num ** 2);
console.log(result);

【実行結果】

[1, 4, 9]

参考

書籍

解きながら学ぶJavaScriptつみあげトレーニングブック | マイナビブックス 4章

WEBページ

残余引数 - JavaScript | MDN
JavaScript: 通常の関数とアロー関数の違いは「書き方だけ」ではない。異なる性質が10個ほどある。 #JavaScript - Qiita

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?