LoginSignup
19
21

More than 5 years have passed since last update.

JavaScript の == と === の違いを詳しくまとめてみる

Last updated at Posted at 2017-09-13

はじめに

JavaScript『 等しい 』 には 等しい ==厳密に等しい === の2種類があります。

等価演算子 ==

左辺と右辺の型 データ型 評価基準
同じ 文字列・数値・論理型 単純に値が等しいか
同じ 配列・オブジェクト 参照先が等しいか
同じ null・undefined すべて true
異なる 文字列・数値・論理型 文字列・論理型を数値に変換して比較
異なる オブジェクト リテラルに変換して比較
console.log('5' == 5)  // true
console.log(1 == true) // true
console.log(['vue', 'angular', 'react'] == ['vue', 'angular', 'react'])  // false 参照先が等しくない
console.log('3.14e2' == 314) // true 浮動小数点により'3.14e2'→'314'
console.log('0x10' == 16) // true '0x10'が16進数表現とみなされる

== は値を等しいとみなせないか頑張ります。

厳密等価演算子 ===

厳密等価演算子はデータ型を変換しません。

console.log('5' === 5)  // false
console.log('3.14e2' === 314)  // false
console.log('0x10' === 16)  // false

等価演算子==true が返っていたものが === ではいずれも false が返りました。
javaScriptの寛容さはアプリを開発する際には予期せぬバグを生み出すことがあるので比較は === で行ったほうが良いそうです。

'5' === 5false になるのは文字列の5と数値5が異なるためです。
数値と文字列を比較する際は === で比較し明示的に型変換を行うことが一般的なようです。

index.html
<input type="number" id="numbox">
<input type="button" id="btn" value="ボタン">
script.js
window.addEventListener('DOMContentLoaded', () => {
  const btn = document.getElementById('btn');
  btn.addEventListener('click', () => {
    const numbox = document.getElementById('numbox')
    const target = 5

    // 数値と文字列の厳密比較は必ずfalseが返るので数値に変換する
    console.log(target === Number(numbox.value)) // true 
  }, false)
}, false)

無題.png

【おまけ】 switch 文は === で比較される

const a = undefined
const b = null
console.log(a == b)  // true
console.log(a === b)  // false
switch (a) {
  case b:
    console.log('some')  //     実行されない
    break
}

参考

19
21
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
19
21