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のダブル否定演算子(!!)とは

Posted at

JavaScriptやGoogle Apps Scriptを書いていると、
便利そうなものをAIが提案してきた。

const isValid = !!value;

いずれ自分が忘れると思うのでいつも通り自分用のメモとして残す。

そもそも「!」は否定

単一の ! は否定(NOT)演算子
真偽を反転する

!true   // false
!false  // true

! は「真偽値に変換してから反転」しているのがポイント

真偽値に変換する例

!123        // false(数値はtrue扱い → 反転してfalse)
!0          // true(0はfalse扱い → 反転してtrue)
!""         // true(空文字はfalse扱い → 反転してtrue)
!"hello"    // false(中身のある文字列はtrue扱い → 反転してfalse)
!undefined  // true
!null       // true

! はまず値をBoolean型に変換してから反転する機能がある。

!!(ダブル否定)の登場

最初の ! で真偽を反転、
次の ! でもう一度反転。

つまり結果的に真偽値変換だけをすることになる。

!!true        // true
!!false       // false
!!"text"      // true
!!""          // false
!!0           // false
!!123         // true
!!null        // false
!!undefined   // false

よくある事例:型を明示的にBooleanにしたい

const hasValue = !!sheet.getRange("A1").getValue();

hasValue は常に true  false のどちらかになる


// 配列チェック

const isEmpty = !array.length; // 空配列ならtrue
const hasItems = !!array.length; // 要素があればtrue


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?