0
0

[Javascript]関数の書き方

Last updated at Posted at 2023-09-27

概要

JavaScriptで関数を定義する方法は大きく分けて2つ「関数宣言」と「関数式」がある。
違いはFunctionオブジェクトの生成タイミングで「関数宣言」ではコードブロックが実行する前に生成され、「関数式」はコードブロック実行時に生成される。
そのため関数宣言では関数定義より前に記述しても関数を呼び出せる。

function【関数宣言】

functionというキーワードを使って、関数名を定義する。
どのタイミングでも呼び出せる。

function sample(args){
  console.log(args);
}
sample('hello world');

関数リテラル【関数式】

関数名を変数のように定義し、その中に関数の機能を代入するようなイメージ。
定義後でしか呼び出せない。

const sample = function(args){
  console.log(args);
};
sample('hello world');

アロー関数【関数式】

アロー関数は「=>」というキーワードを使って記述する方法。
定義後でしか呼び出せない。

const sample = (args) => {
  console.log(args);
};
sample('hello world');

参考

【JavaScript】色々な関数の書き方一覧
JavaScriptでよく見かける3種類の関数の書き方

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