Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

1. JavaScript Objects > Complex Objects Are Equal by Reference

Complex Objects Are Equal by Reference

When comparing complex objects, they are equal only when they reference the same object (i.e., have the same address). Two variables containing identical objects are not equal to each other since they do not actually point at the same object.

Below, objectFoo and objectBar have the same properties and are, in fact, identical objects, but when asked if they are equal via ===, JavaScript tells us they are not.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

var objectFoo = {same: 'same'};
var objectBar = {same: 'same'};

/* logs false, JS does not care that they are identical 
and of the same object type */
console.log(objectFoo === objectBar);

// how complex objects are measured for equality
var objectA = {foo: 'bar'};
var objectB = objectA;

console.log(objectA === objectB); /* logs true because they reference 
                                  the same object */

</script></body></html>

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint