Homeconst t="undefined"!=typeof HTMLImageElement&&"loading"in HTMLImageElement.prototype;if(t){co..." />Homeconst t="undefined"!=typeof HTMLImageElement&&"loading"in HTMLImageElement.prototype;if(t){co..." />The Difference Between Values and References in JavaScript
Home
Dmitri Pavlutin
I help developers understand Frontend technologies
Post cover

The Difference Between Values and References in JavaScript

Posted March 23, 2021

In JavaScript, you can pass by value and by reference.

The main difference between the two is that passing by value happens when assigning primitives while passing by reference when assigning objects.

Let's discuss values and references in more detail in this post.

1. Understanding primitive and objects

JavaScript provides 2 categories of data types: primitives and objects.

The primitives are numbers, booleans, strings, symbols, and special values null and undefined.


// Primitives
const number = 10;
const bool = false;
const str = 'Hello!';
const missingObject = null;
const nothing = undefined;

The second category is objects. Particularly the plain object, arrays, functions, and more — are all objects.


// Objects
const plainObject = {
prop: 'Value'
};
const array = [1, 5, 6];
const functionObject = (n1, n2) => {
return n1 + n2;
};

Saying it differently, anything that is not a primitive value is an object.

2. Values

The simple rule of passing by value is that all primitive values in JavaScript are passed by value. Simple as that.

Passing by value means that every time you assign a value to a variable, a copy of that value is created. Every single time.