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
  • //Compare Numbers
    var a = 10;
    var b = 10;
    
    var c = new Number(10);
    
    console.log(a == b); //true
    console.log(a === b); //true
    
    console.log(a == c); //true
    console.log(a === c); //false
    		
    Compare Objects
    //Compare Objects Addresses
    var jangoFett = {
        	occupation: "Bounty Hunter",
        	genetics: "superb"
    };
    
    var bobaFett = {
        	occupation: "Bounty Hunter",
        	genetics: "superb"
    };
    
    var callMeJango = jangoFett;
    
    console.log(jangoFett == bobaFett); //false
    console.log(callMeJango == jangoFett); //true
    
    console.log(jangoFett === bobaFett); //false
    console.log(callMeJango === jangoFett); //true
    		
    var person_1 = {name: 'Lin', age: 39};
    var person_2 = {name: 'Lin', age: 39};
    var person_3 = person_1
    
    function isEquivalent(a, b) {
    	// If two variables point to the same object
    	if (a === b)
    		return true;
    
        // Create arrays of property names
        var aProps = Object.getOwnPropertyNames(a);
        var bProps = Object.getOwnPropertyNames(b);
    
        // If number of properties is different,
        // objects are not equivalent
        if (aProps.length != bProps.length) {
            return false;
        }
    
        for (var i = 0; i < aProps.length; i++) {
            var propName = aProps[i];
    
            // If values of same property are not equal,
            // objects are not equivalent
            if (a[propName] !== b[propName]) {
                return false;
            }
        }
    
        // If we made it this far, objects
        // are considered equivalent
        return true;
    }
    
    console.log(isEquivalent(person_1, person_2)); // true
    console.log(isEquivalent(person_1, person_3)); // true
    		
    Reference
  • Object Equality in JavaScript