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.

stringやnumberがtruesyかfalsyかでbooleanを代入したい時

Posted at

stringやらnumberやらがtruesyかfalsyかでbooleanを代入したい時があると思うが、
そういう時に

if (str) {
  object.bool = true
} else {
  object.bool = false
}

とか

object.bool = str ? true : false

と書くのがとても煩わしく感じた。

これは、実は

object.bool = !!str

これで対応できる。

しくみ

特別な構文を使っているとかそういうわけではない。

!str 

こう書くと「””」ならtrue、「"hoge"」ならfalseになる。
それをさらに反転しているだけ。

!!str 

「””」なら!true、つまりfalseが取れるというわけ

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?