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.

【JavaScript】==と===の違いについて

Last updated at Posted at 2021-08-31

はじめに

アウトプットが苦手な自分が練習の一環として記事を書いてみる。

第五回目です。

今回はJavaScriptで「==」と「===」の違いについて書いていきます。

等価演算子 (==)

等価演算子は方は比較するもの同士の型を見て、型が異なる場合は同じ型に変換してから比較を行います。
例えば数値の「1」と文字列の「'1'」を比較する場合、文字列の「'1'」を数値型に変換してから比較する挙動となります。

等価演算子
console.log('1' == 1); // true
console.log('0' == 0); // true
console.log(true == 1); // true
console.log(false == 0); // true
console.log('' == 0); // true
console.log(undefined == null); // true

厳密等価演算子 (===)

厳密等価演算子は等価演算子と違い型が異なる同士の場合でも型の変換が行われません。
よって先ほど等価演算子でtrueが返っていたものが厳密等価演算子ではfalseが返ってきます。

厳密等価演算子
console.log('1' === 1); // false
console.log('0' === 0); // false
console.log(true === 1); // false
console.log(false === 0); // false
console.log('' === 0); // false
console.log(undefined === null); // false

まとめ

以上になります。

今回のように等価演算子と厳密等価演算子で結果が異なること場合があるため、
比較を行う際はどのようなことをしたいのか考え使用する演算子を使い分ける必要があります。

個人的には等価演算子だと空文字が0と同じ値として処理されてしまい予期せぬ挙動に
なってしまうことがたまーにあったりしたので、
基本的には厳密演算子が使える言語の場合は厳密演算子を使用するようにしています。

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?