Why you must understand the difference between Reference and Value in JS

·

2 min read

2 categories of data types in JavaScript

There are two types - primitives and objects or (data types passed by Value and passed by Reference.

Values

Passing by value occurs when assigning primitives.

Value types:

  • Number
  • Boolean
  • Undefined
  • Null
  • String
  • Symbol

References

Passing by reference occurs when assigning objects.

Reference types:

  • Objects
  • Functions
  • Arrays
  • Class instances

The difference between value and reference

When you want to compare objects understanding the difference between values and references is important!

When you use the strict comparison operator "===", two variables having values are equal if they have the same value.

      let a = 1
      let b = 1
      a === b  //true
      a == b    // true
      a === 1  //true

When you assign variable b to a JS copies the value, you have two different "1", they are indepentent!

      let a = 1
      let b = a //copies the same value to variable b
      function add(element){
           element++
      }
      add(a) // a = 2 
      // b = 1

What about reference? The comparison operator "===" works differently when comparing 2 references. References are equal only if they reference exactly the same object.

     const person1 = { name: Adrian }
     const person2 = { name: Adrian }
     const person1Ref = person1

     console.log(person1 === person2)         // false
     console.log(person1 === person1Ref)   // true

The comparison operator returns true only when comparing references pointing to the same object: person1 === person1Ref or person1 === person1.

Why you must understand the difference?

You must understand it when comparing objects. It will make your work easier and avoid mistakes.

You can also compare their structure rather than their reference.