The phrases mentioned in the title of this post get thrown around when discussing features of a language. Most languages are one or the other...but not so with JS.
Let's explore what these concepts mean and then see some code snippets to explore the implications.
This post assumes knowledge of const
and let
to declare variables and basic knowledge of JS Objects and .
notation.
I'll also assume that you understand how to log
values with console.log()
.
Pass by 'Copy'
Primitive data types, such as strings are passed by copy. This means that each variable references it's own 'copy' of any given primitive value.
let myCar = 'Mazda';
/**
* Let's get 'you' the 'same' car as me.
* Since we are working with PRIMITIVES,
* this means that 'your car' will be a separate 'copy' of mine.
*/
let yourCar = myCar; // 'you' have your own 'Mazda.'
// I am replacing my car.
myCar = 'Ford'
console.log(myCar); // 'Ford'
// Your car is the same
console.log(yourCar); // 'Mazda'
Since we worked with primitives above, even though 'cars' 'looked the same,' for a time, we were referencing 2 different copies.
Pass by 'Reference'
JS Objects, however, are pass by reference. This means that they share the exact same 'spot' in memory, and mutations (changes) will be reflected in both variables.
const myCar = { make: "Mazda" };
/**
* Since we are working with OBJECTS,
* this time you are 'sharing' my car - not getting your own 'copy.'
* So it's now 'our' car...the same REFERENCE.
*/
const yourCar = myCar;
// I got a new car...so that means you did too - via the same REFERENCE.
myCar.make = "Mercedes";
console.log(myCar.make); // "Mercedes"
console.log(yourCar.make); // "Mercedes"
Understanding the concepts 'pass by copy' and 'pass by reference' will help you understand not just JS, but many other programming languages. Understanding this 'inconsistent' behavior within JS itself can help you squash 🐛s. 🤓
Top comments (0)