Comparison
Operators
  • ==, equal to
  • ===, equal value and equal type
  • !=, not equal
  • !==, not equal value or not equal type
  • >, <, >=, <=
  • Primitives, like strings and numbers, are compared by their value
  • Objects, like arrays, dates, and plain objects, are compared by their reference
    1. //Compare Numbers
    2. var a = 10;
    3. var b = 10;
    4.  
    5. var c = new Number(10);
    6.  
    7. console.log(a == b); //true
    8. console.log(a === b); //true
    9.  
    10. console.log(a == c); //true
    11. console.log(a === c); //false
    Compare Objects
    1. //Compare Objects Addresses
    2. var jangoFett = {
    3. occupation: "Bounty Hunter",
    4. genetics: "superb"
    5. };
    6.  
    7. var bobaFett = {
    8. occupation: "Bounty Hunter",
    9. genetics: "superb"
    10. };
    11.  
    12. var callMeJango = jangoFett;
    13.  
    14. console.log(jangoFett == bobaFett); //false
    15. console.log(callMeJango == jangoFett); //true
    16.  
    17. console.log(jangoFett === bobaFett); //false
    18. console.log(callMeJango === jangoFett); //true
    1. var person_1 = {name: 'Lin', age: 39};
    2. var person_2 = {name: 'Lin', age: 39};
    3. var person_3 = person_1
    4.  
    5. function isEquivalent(a, b) {
    6. // If two variables point to the same object
    7. if (a === b)
    8. return true;
    9.  
    10. // Create arrays of property names
    11. var aProps = Object.getOwnPropertyNames(a);
    12. var bProps = Object.getOwnPropertyNames(b);
    13.  
    14. // If number of properties is different,
    15. // objects are not equivalent
    16. if (aProps.length != bProps.length) {
    17. return false;
    18. }
    19.  
    20. for (var i = 0; i < aProps.length; i++) {
    21. var propName = aProps[i];
    22.  
    23. // If values of same property are not equal,
    24. // objects are not equivalent
    25. if (a[propName] !== b[propName]) {
    26. return false;
    27. }
    28. }
    29.  
    30. // If we made it this far, objects
    31. // are considered equivalent
    32. return true;
    33. }
    34.  
    35. console.log(isEquivalent(person_1, person_2)); // true
    36. console.log(isEquivalent(person_1, person_3)); // true
    Reference
  • Object Equality in JavaScript