Comparison Operators Explained
Learn JS Fundamentals to jQuery & Pure DOM Scripting
Decision tree for
> maybe to compare
===
with primitives
"comparison by value" - compares values in memory
===
with objects
check by reference -> checks their addresses in memory so
var obj1 = {}
var obj2 = {}
obj1 === obj2
returns falsebecause these two objects are not stored at the same address in memory (doesn't continue checking their values)
note: every variable in JavaScript has an address allocated in memory that points to an another address in memory that holds it's value
Decision tree for ==
Goes through this (if
false
move to next step)- types the same (like two strings, if yes:
===
)? - both
null
orundefined
(if yes returntrue
)? - a string == a number -> if yes : see logic below
- boolean == anything -> if yes see logic below
- object == string or number -> if yes, do this with the object:
.toString()
or.valueOf()
if comparing string == number or boolean == anything then convert the types with these table (
e.g. boolean true
will become 1
):- undefined -> NaN;
- null -> 0;
- true -> 1,
- false -> 0,
- string -> # || NaN (e.g.
"1"
will become1
)
===
Summary
1. types the same? if false return false otherwise
2. primitive? if true: bitwise comparison if not primitive (i.e. an object) address comparison
when to use
===
> never
null
to undefined