Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

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?

三項演算子の省略形には気をつけろ

Last updated at Posted at 2024-10-15

初めに

PHPやjavascriptなどの三項演算子で

const hoge = x ? x : y

などと書く場合に省略形として

const hoge = x ?? y

とする場合がありますが、この二つの結果が違ってくる場合があります

実際に試してみる

例えば以下の場合は同じ結果です

const x = 1
const y = 999
console.log(x ? x : y)
> 1

const x = 1
const y = 999
console.log(x ?? y)
> 1

しかしx = 0の場合

const x = 0
const y = 999
console.log(x ? x : y)
> 999

const x = 0
const y = 999
console.log(x ?? y)
> 0

となり結果が異なります

なぜか

??は正式名称Null合体演算子と言い、名前の通りnull(undefined)かどうかを見てるためです

終わりに

この結果から、変数に0や空文字がありえて、かつ0や空文字もfalseにしたい場合は

x ? x : y

もしくは

x || y

を使ったほうがいいと思います
言語によってはエルビス演算子?:でも良いかと思います

0
0
1

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

@tak_iwasaki's pickup articles

Comments

eufss0183
@eufss0183

NULL合体演算子は三項演算子の省略形ではないので、

PHPやjavascriptなどの三項演算子で

const hoge = x ? x : y

などと書く場合に省略形として

const hoge = x ?? y

とする場合がありますが

この前提がそもそも間違いです。

1

Let's comment your feelings that are more than good

Qiita Conference 2024 Autumn will be held!: 11/14(Thu) - 11/15(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

Takahiro Anno, Masaki Fujimoto, Yukihiro Matsumoto(Matz)

View event details

Being held Article posting campaign

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?

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address