Pass-by-reference/value is something that every developer uses on a daily basis, but the more experienced you are, the less you really think about it. This guide shortly describes what the difference is for them in JavaScript.

Warning! Game of Thrones spoilers ahead!

What does pass-by-* mean?

Both terms refer to the way a variable is treated after it's been passed as a parameter to a function.

Let's take a look at the following code:

const changeCharacterName = (character) => {
    character = 'aegon';
};

let thatGOTCharacter = 'jon';
changeCharacterName(thatGOTCharacter);
console.log(thatGOTCharacter); // 'jon'

The passed variable character can either be passed-by-value or passed-by-reference. In this example it's passed-by-value, but more to that in a bit.

Primitive types in JavaScript

Ever heard the saying "Everything in JS is an object"? Well that's not entirely true. There are the data types that are not objects

  • Number
  • String
  • Boolean
  • Symbol
  • null
  • undefined

Everything that is not a primitive type is an object.

Pass-by-value

The value of the variable is being passed onto the function.

Now what's the difference between the two? Pass-by-value means that only the value of the variable is being passed. A copy of the original variable is being made and you can work with this copy in the function. Changes to this only affect the variable in the current scope (function).

That's why in the first example, the value is still 'jon', even after changeCharacter has been called.

Pass-by-reference

Only the reference is being passed onto the function.

This is the opposite of pass-be-value. Because not the value is being passed, but a reference of the object. No copy is being created! So the function will only know where the object is and will work with that. So, if the object is being mutated, the original object changes.

So how can we change our code from the beginning so the name of that GOT character gets changed? (Yes, we need an object!)

const changeCharacterName = (character) => {
    character.firstname = 'aegon';
    character.lastname = 'targaryen';
};

let thatGOTCharacter = {
    firstname: 'jon',
    lastname: 'snow'
};
changeCharacterName(thatGOTCharacter);
console.log(thatGOTCharacter.firstname); // 'aegon'

Summary

This is not a that complicated topic and it actually feels quite natural using it, once you understand how it works. But it's important to know what happens under the hood.

Things to remember:

  • For primitive types variables, only the value is being passed to a function
  • Changes on a primitive type variable only affects it's scope (function)
  • For object variables, the reference of the object is being passed to a function
  • Changes on an object in a function affects the original object.

There is more to this topic, but this is only a basic guide. So this is where I will stop for now.

Photo by Caleb Lucas on Unsplash