DEV Community

Steve Latham
Steve Latham

Posted on

Just passing by

This is a note-to-self and any other passers-by.

By Value

Follow the below example...


let a = 42;    // define variable "a" as 42
let b = a;     // define b to be equal to a

// log out the results
console.log(a);    // => 42
console.log(b);    // => 42 

// now if we give b the value of 100
b = 100;

// log out the results again
console.log(a);    // => 42
console.log(b);    // => 100

The point to remember is that when we assign "b" to equal "a" on line 2, what happens is the value (42 in this case) stored in "a" is copied to "b". It is said to be passed by value.

When we eventually give "b" another value (100 in this example), it has no effect on the variable "a". We can see "a" is still 42 and "b" has now changed to 100.

By Reference

Now consider this familiar(ish) example...


let a = {value: 42};    // define variable "a" to be an object
let b = a;              // define b to be equal to a

// log out the results
console.log(a);    // => {value: 42}
console.log(b);    // => {value: 42} 

// now if we change a property of b
b.value = 100;

// log out the results again
console.log(a);    // => {value: 100}
console.log(b);    // => {value: 100}

The point to remember here is when we assign "b" to equal "a" on line 2, what happens is a reference to the value of "a" is passed to "b". Then both "a" and "b" point to the value (in this case the object {value: 42}). They are both just a reference to the object {value: 42} stored in memory. This is demonstrated when we change the value of "b.value" to 100, we see "a" also shows this change.

So what is going on?

Well, it depends on the value that is stored in the variable. If you are dealing with a primitive type - say a number or a string as in the first example, then pass by value is used. For objects and arrays, on the other hand, pass by reference is used.

To boil it down: If you pass an array or an object to a variable or a function, you are just passing a reference to it.

So if we look at the following example and read through the code...

// define a function that takes two parameters
const myFunction = (x,y) => {

  x[3] = 42;    // change the 4th array element to 42
  y = 100;     // change y to equal 100  

}

let a = [1,2,3,4];    // define a to be an array
let b = 42;           // define b to be the number 42
myFunction(a,b);      // call the function with a and b as the arguments

// log out the result on a and b of calling the function
console.log(a);    // => [1,2,3,42]     
console.log(b);    // => 42

We can see that "a" is mutated by the function, but "b" is not. The primitive number 42 is passed to the function by value. So "y" is a copy of "b", then "y" gets changed to 100 leaving "b" unchanged.

On the other hand, the reference to the array "a" is passed to the function, the array is then mutated as "x" and "a" are just pointers to the original array.

Clear as mud!

Top comments (0)