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?

JavaScriptのIIFEを理解する

Posted at

概要

IIFEはImmediately Invoked Function Expressionの略です。

  • Immediately: 即時に
  • Invoked: 実行される
  • Function: 関数
  • Expression: 式

つまり、定義した瞬間に実行される関数式のことです。

日本語では 即時実行関数式 と呼ばれます。

(() => {
  console.log("IIFE");
})();

サンプルコード

ifやswitchなどを式として扱いたい場合

JavaScriptでは ifswitch文(statement) であり、
そのままでは値を返せません。

// ❌ これはできない
const value = if (flag) {
  "A";
} else {
  "B";
};

このような場合に、IIFEを使うと「式」として扱えます。

const value = (() => {
  if (flag) {
    return "A";
  }
  return "B";
})();

ReactのuseEffectなど、非同期関数を受け取らない引数に非同期処理を渡したい場合

useEffect戻り値に cleanup 関数か undefined しか返せない ため、
直接 async 関数を渡せません。

// ❌ エラー
useEffect(async () => {
  await fetchData();
}, []);

このような場合、async IIFE を使うと自然に書けます。

useEffect(() => {
  (async () => {
    await fetchData();
  })();
}, []);

非同期処理を即時実行したいが、構文上asyncを使えない場面でよく使われるパターンです。

letをconstへ

IIFEを使うと、letconst に置き換えられる場合があります。

let result;

if (flag) {
  result = "A";
} else {
  result = "B";
}

IIFEを使うと、次のように書けます。

const result = (() => {
  if (flag) {
    return "A";
  }
  return "B";
})();
  • 再代入を防げる
  • 値の決定ロジックを一箇所にまとめられる

といったメリットがあります。

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?