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?

More than 3 years have passed since last update.

【JS】真偽値を確認する方法。ビックリマーク2つ(!!)の意味。

Last updated at Posted at 2021-01-08

個人メモです。

変数や処理の冒頭にビックリマークを2つ!!つけると、真偽値の状態を確認できる。

x = 100
console.log(!!x)
//true

arr = [1,2,3]
console.log(!!arr)
//true

変数に!(反転の意)一つをつけると、値が存在すればfalse、存在しなければtrueを返す。

さらにこの戻り値にビックリマークをつけて!!とすれば、実際の状態にあった真偽値が返る。

▼注意点
0や空の配列はfalseで返る。

x = 0
console.log(!!x)
//false

arr = []
console.log(!!arr)
//false

if文の条件式で変数を指定した場合に、tureかfalseどっちになっているかを確認するのに便利。

##Boolean()
!!値Boolean(値)と同じ。
可読性の観点ではBooleanの方がわかりやすい。

x = 100
console.log( Boolean(x) )
//true

arr = [1,2,3]
console.log( Boolean(arr) )
//true
1
0
2

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?