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.

[JS] アロー関数

Posted at

無名関数

2つの出力結果は同じです

const hello = function(name = 'Shun') {
  console.log('hello' + name);
}

hello();
function hello(name = 'Shun') {
  console.log('hello' + name);
}

hello();

Image from Gyazo


が、
1つ目の、実行後に変数の宣言があった場合にはエラーが発生します

hello();

const hello = function(name = 'Shun') {
  console.log('hello' + name);
}

Image from Gyazo

JavaScriptの動きとしては、関数を一度ファイル全体で確認してから処理が行われるので、
2つ目の関数宣言はエラーが発生しません

hello();

function hello(name = 'Shun') {
  console.log('hello' + name);
}

Image from Gyazo

この違いは認識しておきましょう

アロー関数

=>を用います
{ }内が一行の場合は{ }を省略できます
nameにデフォルト値がない場合、かつ関数の引数が1つの場合には( )も省略できます

const hello = name => console.log('hello' + name);

hello('Shun');

Image from Gyazo


nameにデフォルト値がある場合

const hello = (name + 'Shun') => console.log('hello' + name);

hello();

Image from Gyazo


かつ関数の引数が2つの場合

const hello = (name, age) => console.log('hello' + name + age);

hello('Shun', 20);

Image from Gyazo

戻り値

const hello = (name, age) => 40;
console.log(hello());

Image from Gyazo

これは

const hello = (name, age) => {
  return 40;
}

console.log(hello());

と同じ意味です

実用的な使い方

これを

const arry = [1,2,3,4,5,6];

arry.forEach(function(value) {
  console.log(value);
})

こうします

const arry = [1,2,3,4,5,6];
arry.forEach(value => console.log(value));

Image from Gyazo

出力結果は同じですが、さっぱりしましたね

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?