Javascript - Object Equality


This page is talking about Equality for an object in the sense, not a primitive.



For a comparison between object, both == and === object equality operator will simply check whether the references match.

They will not compare the content (ie not anything about the underlying values)

valueOf is called if one side of the equality comparison if not an object. verifies the value.

  • in case of the primitive, this is the value
  • in other cases, this is the reference

Syntax:, value2);
let foo = { a: 1 };
let bar = foo;
console.log(, foo));              // true
console.log(, bar));              // true
console.log(, { a: 1 }));              // false
  • Special Values, null);            // true, undefined);  // true, window);        // true

Equality Operator Example


function Employee(name) { = name;
    this.dept = 'general';
    this.valueOf = function(){
let employee1 = new Employee('nico');
let employee2 = new Employee('nico');
  • Test
console.log("The variable employee1 has the type "+(typeof employee1 ));
console.log("The variable employee1 has the valueOf "+employee1.valueOf());
console.log("They are not equal "+(employee1 == employee2));
console.log("But their value is "+(employee1.valueOf() == employee2.valueOf()));


var a = [1,2,3];  
var b = [1,2,3]; 
console.log("The array a has the type "+(typeof a));
console.log("The array a in a string format is "+a.toString()+ "( valueOf() )" );
  • The string representation of an array is element1, …, elementn
var c = "1,2,3"; 
console.log("The variable c has the type "+(typeof c));
  • Equality
console.log( a == c ); // true - same value as string
console.log( b == c ); // true - same value as string
console.log( a == b ); // false (not the same reference)

Powered by ComboStrap