Compare by value vs by reference - Javascript Language Basics

Javascript examples for Language Basics:Introduction

Introduction

JavaScript primitives (the built-in types, such as strings and numbers) are compared by value, but JavaScript objects are compared by reference.

The following code shows how JavaScript handles equality and identity tests for objects.

Demo Code

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
    </head>
          <body>
              <script type="text/javascript">

                  var myData1 = {
                      name: "java2s.com",
                      topic: "CSS",
                  };/*from   www.j a v  a 2  s  .  c  o m*/

                  var myData2 = {
                      name: "java2s.com",
                      topic: "CSS",
                  };

                  var myData3 = myData2;

                  var test1 = myData1 == myData2;
                  var test2 = myData2 == myData3;
                  var test3 = myData1 === myData2;
                  var test4 = myData2 === myData3;

                  document.writeln("Test 1: " + test1 + " Test 2: " + test2);
                  document.writeln("Test 3: " + test3 + " Test 4: " + test4);
              </script>
          </body>
      </html>

Related Tutorials