Course contents
- 01Variables
- 02Primitive Data Types
- 03Operators
- 04Conditionals
- 05Arrays
- 06Array methods and properties
- 07Objects
- 08Functions
- 09Callbacks
- 10Arrow functions
- 11Promises
- 12Async and await
- 13Loops
- 14DOM Manipulation
- 15Syntax parser
- 16Execution context and hoisting
- 17Call stack
- 18WebAPI and setTimeout
- 19Closures
- 20Function Constructors and Prototypes
- 21By value vs by reference
By value vs by reference
Almost everything in JavaScript is an object, such as arrays and functions. An object is a collection of name/value pairs, which values can be anything, meaning that it can be either a primitive type or another object. Objects have properties and methods (functions that sit on an object) and are sitting in the memory with references to the spots where these properties/methods “live”. You have access to those properties and methods in memory.
All primitive types interact by value.


First, we declare two variables a and b. Then, we set b equal to a, which is 4 at that point. Later, we give a the value of 2. At this point, b is still 4! This happens because b has its own space in memory!
All nonprimitive values interact by reference when setting them equal to each other or passing them to a function.


In memory, this would look something like:

Both c and d have the same value, which points to the same address.
Variable c holds a reference to an array (object) . Later, we assign d with the same reference that c has to the object. If you later change the value of that variable by, for example, pushing an element to that array, it also means that that property is changed for all the other variables. They point to the actual same object, and not a copy of it.
References and further reading
- MDN: JavaScript data typesPrimitive values compared with objects.
- MDN: ObjectWhy object references behave the way they do.