DEV Community 👩‍💻👨‍💻

Cover image for Reference vs. Primitive Values
Juan Restrepo
Juan Restrepo

Posted on

Reference vs. Primitive Values

Primitive Types

A primitive data type is defined by the programming language. Primitive data types consist of numbers, strings, boolean, null, and undefined.

let a = 1; 
let b = 1; 

a === b; // true

let string1 = 'hi';
let string2 = 'hi';

string1 === string2; // true
Enter fullscreen mode Exit fullscreen mode

Variables holding the same value and same data type will always return true in a condition as long a strict operator is used (===). This is not the same for reference types.

Reference Types

Reference types are nonprimitive types and are not defined by the user. Objects are considered a reference type; furthermore, arrays are also objects. Objects are created by the programmer.

let object1 = {value:1};
let object2 = {value:1};
let object3 = object1; 

object1 === object2; // false
Enter fullscreen mode Exit fullscreen mode

When we assign a key-value pair to object1 and assign the same key-value pair to object2 and check to see if they are equal we get false. This is a bit confusing since this works for primitive types. Every time we create an object we are creating a space in memory to hold the information and a reference to that object in memory. Creating 2 objects creates 2 different references and 2 different addresses where the objects will be saved. Even though the objects contain identical key-value pairs this is the reason they are considered different.

let object1 = {value:1};
let object2 = {value:1};
let object3 = object1; 

object3 === object1; // true; 
Enter fullscreen mode Exit fullscreen mode

Now if we take a look at object3 variable the value assigned to it is object1. A new object is not being created this time. Only a reference to object1 is in the value of object3. Object1 and object3 point to the same address; therefore, the same object. Now doing a conditional statement will return true.

let object1 = {value:1};
let object2 = {value:1};
let object3 = object1; 

object1.value = 2; 

console.log(object3.value)// 2;  
Enter fullscreen mode Exit fullscreen mode

Changing the properties of object1 will also change the properties of object3 since they are the same object.

Reference types can be a bit difficult to understand, but I hope after reading this blog, it will be clearer in your mind.

Top comments (0)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

⭐️🎀 JavaScript Visualized: Promises & Async/Await

async await