1
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は省略がお好き【アロー関数】

Last updated at Posted at 2024-03-07

JavaScriptの関数の書き方を整理してみました。

通常の関数

function sample (str) {
    return str;
};

console.log(sample("関数sampleにこの文を引数として渡して出力します。"));
const sample = function (str) {
    return str;
};

console.log(sample("関数sampleにこの文を引数として渡して出力します。"));

アロー関数

const sample = (str) => {
    return str;
};

console.log(sample("関数sampleにこの文を引数として渡して出力します。"));

引数が一つの場合は(str)の部分のカッコを省略できる。

const sample = str => {
    return str;
};

console.log(sample("関数sampleにこの文を引数として渡して出力します。"));

処理が1行で返却されている場合は波カッコとrerutnを省略できる。

const sample = str => str;

console.log(sample("関数sampleにこの文を引数として渡して出力します。"));

右辺をオブジェクトにしたい場合は()を使う。

const sample = (num1, num2) => ({
    bust: num1,
    hip: num2
});

console.log(sample(86, 98));

省略例

const sample = function (num1, num2) {
    return num1 + num2;
};

console.log(sample(86, 98));

上述の内容を踏まえ、上記の関数を省略して書くと、以下のようになります。

const sample = (num1, num2) => num1 + num2;

console.log(sample(86, 98));
1
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?