Comparison Operators Explained

In notebook:
FrontEndMasters Advanced JS fundamentals
Created at:
2015-10-08
Updated:
2015-10-08
Tags:
Fundamentals JavaScript
Learn JS Fundamentals to jQuery & Pure DOM Scripting

=== 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 false
because 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)

  1. types the same (like two strings, if yes: ​===​)? 
  2. both null or undefined​ (if yes return ​true​)?
  3. a string == a number -> if yes : see logic below
  4. boolean == anything -> if yes see logic below
  5. 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 become 1​)

​===​ 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 

> maybe to compare ​null​ to ​undefined​