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/TypeScriptで変数初期化とreturnを一文で書く方法

Posted at

特定の条件にマッチする場合の処理を記述する場合、条件に合わないときはブロックの先頭でreturnするという事はよくあります。例えばこんな感じ。

function doTask(params){
  const state = getState(params); // <-(1)
  if (!state) return; // <-(2)
  // let's do task!
}

似たようなことを大量に書くことになるので、この(1)と(2)を一行で書きたくなってきます。
しかし JavaScript/TypeScript では以下のように単純に一行にまとめる事はできません。

function doTask(params){
  const state = getState(params) ?? return;
  // let's do task!
}

ではどうするか。Generatorを使います

function *doTask(params){
  const state = getState(params) ?? (yield);
  // let's do task!
}

returnはダメでもyieldはいけるんですね。ちょっと不思議

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?