Pass By Reference

Hello Everyone,

I’m not sure why, the code example below, a function was created, as indicated by the =>. Why wasn’t an ordinary variable created instead? Is it just to show some variety in code or is there a deeper meaning? I’ve included the topic covered to give context.

Pass By Reference

Objects are passed by reference . This means when we pass a variable assigned to an object into a function as an argument, the computer interprets the parameter name as pointing to the space in memory holding that object. As a result, functions which change object properties actually mutate the object permanently (even when the object is assigned to a const variable).

const spaceship = {
  homePlanet : 'Earth',
  color : 'silver'
let paintIt = obj => {
  obj.color = 'glorious gold'
spaceship.color // Returns 'glorious gold'

what is an ordinary variable?

That is the whole point of this exercise, code sample:

const myString = 'abc'

const myFunc = str => {
    str = 'def'


The string is passed by value (a copy of the original), so the original isn’t modified.

on the other hands, objects can get massive, making a copy could take up a lot of memory. So objects are passed by reference, which means the original object gets modified

Thanks for you reply. When I say ordinary variable, I mean something like:

let paintIt;  
paintIt = 'glorious gold'

I think I’m starting to understand now… the variable above wouldn’t access the ‘spaceship’ function. Functions are more complex, able to hold more data and therefore the spaceship function was able to be accessed and therefore mutate the object. Is that correct?

Variables are just labels, a way for us developers to access the information. What the variable holds is much interesting and relevant.

you mean objects?

No, I meant functions… it’s just that they had been using examples like:

let paintIt;  
paintIt = 'glorious gold'

in the previous examples about Objects and then all of a sudden used a function. I can’t figure out why.

Functions have already been taught, right? so then this exercise combines function and objects to explain passing by reference

1 Like