Skip to content

JavaScript reference equality | Example code

  • by

Use JavaScript equality operator === (and, actually, ==) to test reference equality (e.g., that they refer to the same object/ array/ function).

Check if two vars have the same reference

foo == bar
foo === bar

JavaScript reference equality

Simple example code reference types like objects, == or === operators check its reference only. e.g

<!DOCTYPE html>
<html>
<body>

  <script>
   let a= { text:'my text', val:'my val'}
   let b= { text:'my text', val:'my val'}

   console.log("a == b", a==b)

   b = a;

   console.log("Reference of both variable are same", a==b)

 </script>

</body>
</html>

Output:

JavaScript reference equality
let a= { text:'my text', val:'my val'}
let b= { text:'my text', val:'my val'}

Here a==b will be false as a reference of both variables are different though their content is the same. But if I change it to

a=b

and if I check now a==b then it will be true, since references of both variables are the same now.

More examples

<script>
    var a = 1;
    var b = 1;
    console.log(a == b); // true
    var c = 10;
    var d = "10";
    console.log(c == d); // true
  
  
    const name1 = {
        first_name: "sarah",
    };
  
    const name2 = {
        first_name: "sarah",
    };
  
    console.log(name1 == name2); // false
</script>
<script>
    var a = 1;
    var b = 1;
  
    console.log(a === b); // true
    var c = 10;
    var d = "10";
  
    console.log(c === d); // false
  
    const name1 = {
        first_name: "sarah",
    };
  
    const name2 = {
        first_name: "sarah",
    };
  
    console.log(name1 === name2); // false
</script>

Do comment if you have any doubts or suggestions on this JS equality topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading