JavaScript Comparison Operators

Learning JavaScript can be difficult and more than once I found myself confused on why my code wasn’t working. This post will focus on JavaScript comparisons and the pitfalls of them.

== VS ===

If your learning JavaScript you’e probably noticed the == sign and the === sign. Whats the difference? The double equality operator sign is the equality operator and the === is the identity operator. 

Equality operator ==

The == operator will compare for equality after doing any necessary type conversions

const a = 1;
const b = 1;

a == b // true


const c = "a"
const d = "a"

c == d // true

const e = 1;
const f = 2;

e == f // false


const g = "1"
const h = 1

g == h // true

The Identity Operator

The ===operator will not do the conversion, so if two values are not the same type === will return false.

const a = 1;
const b = 1;

a === b // true


const c = "a"
const d = "a"

c === d // true

const e = 1;
const f = 2;

e === f // false


const g = "1"
const h = 1

g === h //false

Comparing Arrays and Objects

When comparing objects and arrays in JavaScript you can’t use === or == to compare values in an object or array. You can, hover compare refrences to the same instance.

const ob = {
	a:1,
	b:2
}
const ob2 = {
	a:1,
	a:2
}

ob == ob2 // false
ob === ob2 // false


const ob3 = ob

ob == ob3 // true
ob === ob3 // true


const arr = [1,2,3]
const arr2 = [1,2,3]

arr == arr2 //false
arr === arr2 //false

arr3 = arr
arr == arr3 // true
arr === arr3 // true

2 thoughts on “JavaScript Comparison Operators

Leave a Reply

Your email address will not be published. Required fields are marked *